using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using System.Linq; namespace GeneralTools { public class FileDebug : SingletonBaseAttribute { FileStream fileStream_log; StreamWriter streamWrite_log; Queue logQue = new Queue(); string dirPath = ""; public override void IAwake() { if (ConfigHelper.saveLog) { CreateTxt(); Application.logMessageReceived += LogHandler; } } private void CreateTxt() { dirPath = DevicePath.CurrentDirectory + "/Log"; if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); string fileName_log = dirPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "----" + "log" + ".txt"; fileStream_log = new FileStream(fileName_log, FileMode.OpenOrCreate, FileAccess.ReadWrite); streamWrite_log = new StreamWriter(fileStream_log); CheckLogFileNum(dirPath, 20); } public override void IOnApplicationQuit() { if (ConfigHelper.saveLog) { streamWrite_log.Close(); fileStream_log.Close(); Application.logMessageReceived -= LogHandler; } } private void LogHandler(string condition, string stackTrace, LogType type) { logQue.Enqueue(new LogItem() { messageString = condition, stackTrace = stackTrace, logType = type, time = DateTime.Now }); } private void FixedUpdate() { if (logQue.Count > 0) { try { var item = logQue.Peek(); // 取队首元素但先不移除 var timeStr = item.time.ToString("HH:mm:ss.ff"); var logStr = string.Format("{0}-[{1}]{2}======>{3}", timeStr, item.logType, item.messageString, item.stackTrace); streamWrite_log.WriteLine(logStr); streamWrite_log.Flush(); logQue.Dequeue(); // 成功执行了再移除队首元素 } catch (IOException ex) { Debug.Log(ex.Message); } } } /// /// 删除多余的Log, /// /// /// protected void CheckLogFileNum(string path, int maxNum) { List pathList = Directory.GetFiles(path).ToList(); int deleteNum = pathList.Count - maxNum; if (deleteNum > 0) { for (int i = 0; i < deleteNum; i++) { File.Delete(pathList[i]); } } } } } public struct LogItem { /// /// 日志内容 /// public string messageString; /// /// 调用堆栈 /// public string stackTrace; /// /// 日志类型 /// public LogType logType; /// /// 记录时间 /// public DateTime time; }