如何保存Unity中的Log日志
代碼中的debug日志保存本地
using System.Collections; using UnityEngine; using System.IO; public class SaveLog : MonoBehaviour { private float length; Queue queue; private void Awake() { DontDestroyOnLoad(this); LogToFile("Version of the runtime: " + Application.unityVersion, true, false); Application.logMessageReceivedThreaded += OnReceiveLogMsg; queue = new Queue(); } // Start is called before the first frame update void OnReceiveLogMsg(string condition, string stackTrace, LogType type) { string _type = ""; switch (type) { case LogType.Error: _type = "error"; break; case LogType.Assert: _type = "Assert"; break; case LogType.Warning: _type = "Warning"; break; case LogType.Log: _type = "Log"; break; case LogType.Exception: _type = "Exception"; break; default: break; } string msg = "[MSG]:" + condition + "--" + "[station]:" + stackTrace + "-" + "[LogType]:" + _type; queue.Enqueue(msg); } // Update is called once per frame void Update() { CheckLogs(); } void CheckLogs() { if (queue.Count != 0) { LogToFile(queue.Peek().ToString(), true, true,()=> { queue.Dequeue(); }); } } public void LogToFile(string str, bool bwithTime, bool bAppendLineFeed,System.Action callback = null) { if (str == null) return; try { #if UNITY_EDITOR string fname = Application.dataPath + "/Unitylog.txt"; #else string fname = Application.persistentDataPath+ "/Unitylog.txt"; #endif if (fname == "" || fname == null) return; StreamWriter writer = new StreamWriter(fname, true, System.Text.Encoding.Default); if (bwithTime) writer.WriteLine("\r\n\r\n---------" + System.DateTime.Now.ToString()); if (bAppendLineFeed) writer.WriteLine(str); else writer.Write(str); writer.Close(); callback?.Invoke(); } catch { throw; } } }
結果:
補充:Unity3D log寫入文件
關鍵代碼:Application.RegisterLogCallback(logCallBack);
using UnityEngine; using System.IO; public class Logger { string fullPath; public void InitLogger() { fullPath = Application.dataPath + "/output.txt"; if (File.Exists(fullPath)) File.Delete(fullPath); Debug.Log(fullPath.Replace("/output.txt", "")); if (Directory.Exists(fullPath.Replace("/output.txt", ""))) { FileStream fs = File.Create(fullPath); fs.Close(); Application.logMessageReceived += logCallBack; } else { Debug.LogError("directory is not exist"); } } private void logCallBack(string condition, string stackTrace, LogType type) { if (File.Exists(fullPath)) { using (StreamWriter sw = File.AppendText(fullPath)) { sw.WriteLine(condition); sw.WriteLine(stackTrace); } } } private static Logger s_instance; public static Logger instance { get { if (null == s_instance) s_instance = new Logger(); return s_instance; } } }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- None Found