温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Unity怎么自定义保存日志

发布时间:2021-05-13 16:54:42 来源:亿速云 阅读:238 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关使用Unity怎么自定义保存日志,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

using UnityEngine;
using System.IO;
using System;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
 
public class DebugTrace
{
    private FileStream fileStream;
    private StreamWriter streamWriter;
 
    private bool isEditorCreate = false;//是否在编辑器中也产生日志文件
    private int showFrames = 1000;  //打印所有
 
    #region instance
    private static readonly object obj = new object();
    private static DebugTrace m_instance;
    public static DebugTrace Instance
    {
        get
        {
            if (m_instance == null)
            {
                lock (obj)
                {
                    if (m_instance == null)
                        m_instance = new DebugTrace();
                }
            }
            return m_instance;
        }
    }
    #endregion
 
    private DebugTrace()
    {
 
    }
  
    /// <summary>
    /// 开启跟踪日志信息
    /// </summary>
    public void StartTrace()
    {
        if (Debug.unityLogger.logEnabled)
        {
            if (Application.isEditor)
            {
                //在编辑器中设置isEditorCreate==true时候产生日志
                if (isEditorCreate)
                {
                    CreateOutlog();
                }
            }
            //不在编辑器中 是否产生日志由  Debug.unityLogger.logEnabled 控制
            else
            {
                CreateOutlog();
            }
        }
    }
    private void Application_logMessageReceivedThreaded(string logString, string stackTrace, LogType type)
    {
        //  Debug.Log(stackTrace);  //打包后staackTrace为空 所以要自己实现
        if (type != LogType.Warning)
        {
            // StackTrace stack = new StackTrace(1,true); //跳过第二?(1)帧
            StackTrace stack = new StackTrace(true);  //捕获所有帧
            string stackStr = string.Empty;
 
            int frameCount = stack.FrameCount;  //帧数
            if (this.showFrames > frameCount) this.showFrames = frameCount;  //如果帧数大于总帧速 设置一下
 
            //自定义输出帧数,可以自行试试查看效果
            for (int i = stack.FrameCount - this.showFrames; i < stack.FrameCount; i++)
            {
                StackFrame sf = stack.GetFrame(i);  //获取当前帧信息
                                                    // 1:第一种    ps:GetFileLineNumber 在发布打包后获取不到
                stackStr += "at [" + sf.GetMethod().DeclaringType.FullName +
                            "." + sf.GetMethod().Name +
                            ".Line:" + sf.GetFileLineNumber() + "]\n            ";
 
                //或者直接调用tostring 显示数据过多 且打包后有些数据获取不到
                // stackStr += sf.ToString();
            }
 
            //或者 stackStr = stack.ToString();
            string content = string.Format("time: {0}   logType: {1}    logString: {2} \nstackTrace: {3} {4} ",
                                               DateTime.Now.ToString("HH:mm:ss"), type, logString, stackStr, "\r\n");
            streamWriter.WriteLine(content);
            streamWriter.Flush();
        }
    }
    private void CreateOutlog()
    {
        if (!Directory.Exists(Application.dataPath + "/../" + "OutLog"))
            Directory.CreateDirectory(Application.dataPath + "/../" + "OutLog");
        string path = Application.dataPath + "/../OutLog" + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_log.txt";
        fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        streamWriter = new StreamWriter(fileStream);
        Application.logMessageReceivedThreaded += Application_logMessageReceivedThreaded;
    }
 
    /// <summary>
    /// 关闭跟踪日志信息
    /// </summary>
    public void CloseTrace()
    {
        Application.logMessageReceivedThreaded -= Application_logMessageReceivedThreaded;
        streamWriter.Dispose();
        streamWriter.Close();
        fileStream.Dispose();
        fileStream.Close();
    }
    /// <summary>
    /// 设置选项
    /// </summary>
    /// <param name="logEnable">是否记录日志</param>
    /// <param name="showFrams">是否显示所有堆栈帧 默认只显示当前帧 如果设为0 则显示所有帧</param>
    /// <param name="filterLogType">过滤 默认log级别以上</param>
    /// <param name="editorCreate">是否在编辑器中产生日志记录 默认不需要</param>
    public void SetLogOptions(bool logEnable, int showFrams = 1, LogType filterLogType = LogType.Log, bool editorCreate = false)
    {
        Debug.unityLogger.logEnabled = logEnable;
        Debug.unityLogger.filterLogType = filterLogType;
        isEditorCreate = editorCreate;
        this.showFrames = showFrams == 0 ? 1000 : showFrams;
    }
 
}

关于 filterLogType

filterLogType默认设置是Log,会显示所有类型的Log。

Warning:会显示Warning,Assert,Error,Exception

Assert:会显示Assert,Error,Exception

Error:显示Error和Exception

Exception:只会显示Exception

使用

using UnityEngine;
 
public class Test : MonoBehaviour
{
    private BoxCollider boxCollider;
    void Start()
    {
        DebugTrace.Instance.SetLogOptions(true, 2, editorCreate: true); //设置日志打开 显示2帧 并且编辑器下产生日志
        DebugTrace.Instance.StartTrace();
        Debug.Log("log");
        Debug.Log("log", this);
        Debug.LogError("LogError");
        Debug.LogAssertion("LogAssertion");
      
        boxCollider.enabled = false;  //报错 发布后捕捉不到帧
    }
 
    private void OnApplicationQuit()
    {
        DebugTrace.Instance.CloseTrace();
    }
}

如果在编辑器中也设置产生日志,日志文件在当前项目路径下,打包后在exe同级目录下

在打包发布后某些数据会获取不到 例如行号

StackFrame参考

使用Unity怎么自定义保存日志

最后看下效果:

使用Unity怎么自定义保存日志

不足

发布版本 出现异常捕捉不到 行号获取不到

debug版本可以勾选DevelopMend build 捕捉到更多信息

使用Unity怎么自定义保存日志

上述就是小编为大家分享的使用Unity怎么自定义保存日志了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI