当前位置:首页 » 《资源分享》 » 正文

Unity 自定义日志保存_Zero_LJ的博客

19 人参与  2021年09月22日 07:03  分类 : 《资源分享》  评论

点击全文阅读


前言    

   之前unity5.x在代码中写了debug.log..等等,打包之后在当前程序文件夹下会有个对应的"outlog.txt",2017之后这个文件被移到C盘用户Appdata/LocalLow/公司名 文件夹下面。觉得不方便就自己写了个

代码

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参考

最后看下效果:

 

不足

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

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


点击全文阅读


本文链接:http://zhangshiyu.com/post/28309.html

日志  显示  打包  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最新文章

  • 完结文我在恐怖游戏开裁缝铺列表_完结文我在恐怖游戏开裁缝铺(林慕秋)
  • 全书免费谢清禾姜博诚_谢清禾姜博诚全书免费
  • 离婚后我收获真爱,前妻却快死了(秦落音陆轩),离婚后我收获真爱,前妻却快死了
  • 老公把上亿豪宅送养妹后,我把人和房都拆了(顾思思顾言洲)全书免费_(顾思思顾言洲)老公把上亿豪宅送养妹后,我把人和房都拆了后续(顾思思顾言洲)
  • 沈星悦傅时安_沈星悦傅时安
  • 离婚后,居然还能以旧换新?(陈汉李淼淼李思)全书浏览_离婚后,居然还能以旧换新?全书浏览
  • 完结文给女团主播狂刷百万反被骂穷逼,我反手送她队友出道列表_完结文给女团主播狂刷百万反被骂穷逼,我反手送她队友出道(秦薇)
  • 全书浏览老公将我第十个孩子送给情人后,我果断改嫁他绝嗣干爹(苏云遮盛炽)_老公将我第十个孩子送给情人后,我果断改嫁他绝嗣干爹(苏云遮盛炽)全书结局
  • 全文无边怨恨是她活下来的最大动力(江寒静顾榕赫)列表_全文无边怨恨是她活下来的最大动力
  • 全文爸爸死后,消失二十年的妈妈带着儿子回来跟我争家产(顾霆锋顾青卿)列表_全文爸爸死后,消失二十年的妈妈带着儿子回来跟我争家产
  • 霍晚清赵旭然_霍晚清赵旭然
  • 弟弟看的破茧时光沉淀后的深情相拥林悦苏然全书在线

    关于我们 | 我要投稿 | 免责申明

    Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1