Unity5.4 保存日志記錄TXT文件到本地

GitHub:https://github.com/baishuisr1/Unity-Save-the-log

使用方法:
將Write.cs掛載到GameObject
在Awake或start中調用Write.console.LogStart();
輸出方法:Write.Log()


截圖.png

輸出TXT,默認地址為/StreamingAssets/Log文件夾下(注:文件保存只會在打包后輸出,IDE中運行不會保存文件)
Weite.Log()輸出格式:時間-調用類-調用方法-輸出內容
默認輸出格式:時間-信息類型-相關代碼所在地址-內容


截圖.png

源代碼:

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class Write : MonoBehaviour
{
    private static FileStream FileWriter;
    private static UTF8Encoding encoding;
    private static Write _consoleLog;
    private static bool _AllDisplay;
    private static bool _LogDisplay;
    private static bool _WarningDisplay;
    private static bool _LogData;
    private static bool IsIDE;
    private FileInfo fileInfo;
    private string NowTime;

    public static Write console //開啟單例
    {
        get
        {
            if (_consoleLog == null)
                _consoleLog = new Write();
            return _consoleLog;
        }
    }

    /// <summary>
    ///     開始寫入日志,參數(shù)一:是否寫入Warning類型數(shù)據(jù),默認不寫入,參數(shù)二:是否寫入Debug.Log類型數(shù)據(jù),默認不寫入,參數(shù)三:是否寫入全部數(shù)據(jù),默認不寫入,參數(shù)四:是否將Log方法信息輸出到控制臺,默認輸出
    /// </summary>
    /// <param name="WarningDisplay"></param>
    public void LogStart(bool WarningDisplay = false, bool LogDisplay = false, bool AllDisplay = false,
        bool LogData = true)
    {

        if ((FileWriter == null))
        {
            IsIDE = Application.isEditor; //獲取當前場景運行環(huán)境
            _WarningDisplay = WarningDisplay;
            _LogDisplay = LogDisplay;
            _AllDisplay = AllDisplay;
            _LogData = LogData;
            if (IsIDE == false) //判斷當前場景運行環(huán)境,如果是Editor中則不執(zhí)行
            {
                Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
                Directory.CreateDirectory(Application.dataPath + "/StreamingAssets/" + "Log");
                NowTime = DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_");
                fileInfo = new FileInfo(Application.dataPath + "/StreamingAssets/Log/" + NowTime + "_Log.txt");
                //設置Log文件輸出地址
                FileWriter = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
                encoding = new UTF8Encoding();
                Application.logMessageReceived += LogCallback;
            }
        }
    }

    /// <summary>
    ///     替代Debug.log寫入Log信息
    /// </summary>
    /// <param name="_log"></param>
    /// <param name="con"></param>
    public static void Log(object _log)
    {
        if ((_LogDisplay == false) && (_AllDisplay == false))
        {
            if (_LogData)
                Debug.Log(_log);
            if (IsIDE == false)
            {
                try
                {
                    var trace = new StackTrace(); //獲取調用類信息
                    var ClassName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                    var WayName = trace.GetFrame(1).GetMethod().Name;
                    var log = DateTime.Now + " " + "[" + ClassName + "." + WayName + "]" + " " + ":" + " " + _log +
                              Environment.NewLine;
                    FileWriter.Write(encoding.GetBytes(log), 0, encoding.GetByteCount(log));
                }
                catch (Exception)
                {
                    Debug.Log("請檢測是否調用了Console.LogStart方法,或者關閉控制臺Log寫入與所有數(shù)據(jù)寫入項");
                }

            }
        }
        else
        {
            Debug.Log("請檢測是否調用了Console.LogStart方法,或者關閉控制臺Log寫入與所有數(shù)據(jù)寫入項");
        }
    }

    private void LogCallback(string condition, string stackTrace, LogType type) //寫入控制臺數(shù)據(jù)
    {
        string content = null;
        if (_AllDisplay == false)
        {
            if (type.ToString() == "Warning")
                if (_WarningDisplay == false)
                {
                    condition = "";
                    stackTrace = "";
                    content = "";
                }
                else
                {
                    content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " +
                              condition +
                              Environment.NewLine;
                }

            if (type.ToString() == "Log")
                if (_LogDisplay == false)
                {
                    condition = "";
                    stackTrace = "";
                    content = "";
                }
                else
                {
                    content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " +
                              condition +
                              Environment.NewLine;
                }
            if (type.ToString() == "Exception")
                content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " + condition +
                          Environment.NewLine;
        }
        else
        {
            content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " + condition +
                      Environment.NewLine;
        }
        FileWriter.Write(encoding.GetBytes(content), 0, encoding.GetByteCount(content));
        FileWriter.Flush();
    }

    private void OnDestroy() //關閉寫入
    {
        if ((FileWriter != null) && (IsIDE == false))
        {
            FileWriter.Close();
            Application.RegisterLogCallback(null);
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容