Unity 自定义日志保存「建议收藏」

Unity 自定义日志保存「建议收藏」之前unity5.x在代码中写了debug.log..等等,打包之后在当前程序文件夹下会有个对应的”outlog.txt”,2017之后这个文件被移到C盘用户Appdata/LocalLow/公司名文件夹下面。觉得不方便就自己写了个代码:usingUnityEngine;usingSystem.IO;usingSystem;usingSystem.Diag…

大家好,又见面了,我是你们的朋友全栈君。

前言    

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

Unity 自定义日志保存「建议收藏」

最后看下效果:

Unity 自定义日志保存「建议收藏」

 

不足

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

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

Unity 自定义日志保存「建议收藏」

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/157937.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • linux 树型显示文件 tree ls tree 命令

    linux 树型显示文件 tree ls tree 命令

    2021年10月15日
    45
  • 【嵌入式】基于ARM的嵌入式Linux开发总结

    【嵌入式】基于ARM的嵌入式Linux开发总结前言嵌入式知识点复习一嵌入式知识点复习二–体系结构嵌入式知识点复习三–ARM-LINUX嵌入式开发环境嵌入式知识点复习四–arm-linux文件编程嵌入式知识点复习五–arm-linux进程编程嵌入式知识点复习六–arm-linux网络编程嵌入式知识点复习七–linux字符型设备驱动初步嵌入式知识点复习一1、嵌入式系统的一般组成结构2、嵌入式硬件系统的结构(1)…

    2022年6月10日
    37
  • 包裹侠快递单号怎么查询_包裹侠发短信让取快递

    包裹侠快递单号怎么查询_包裹侠发短信让取快递包裹侠快递查询时间:2020-03-04T16:02:28最近,我收到了一个奇怪的包裹。就在星期一的早上,我像往常一样打开大门要拿当天的早报时,发现一个方形的小纸箱孤零零地放在早报上,让我想不注意都不行。没有来信地址、没有署名,有关寄件人的资料一概空白。我惟一能知道的,就是这个包裹指名要寄给我最近,我收到了一个奇怪的包裹。就在星期一的早上,我像往常一样打开大门要拿当天的早报时,发现一个方形的小纸箱…

    2025年6月14日
    4
  • Android蓝牙开发—经典蓝牙详细开发流程[通俗易懂]

    Android蓝牙开发—经典蓝牙详细开发流程[通俗易懂]    Android蓝牙开发前,首先要区分是经典蓝牙开发还是BLE(低功耗)蓝牙开发,它们的开发是有区别的,如果还分不清经典蓝牙和BLE(低功耗)蓝牙的小伙伴,可以先看Android蓝牙开发—经典蓝牙和BLE(低功耗)蓝牙的区别本文是针对经典蓝牙开发的,如果是BLE(低功耗)蓝牙开发,可以看Android蓝牙开发—BLE(低功耗)蓝牙详细开发流程开发流程开启蓝牙 扫描蓝牙 …

    2022年6月15日
    41
  • Could not find method implementation() for arguments [directory ‘libs’]

    Could not find method implementation() for arguments [directory ‘libs’]

    2021年10月1日
    60
  • windows 7 开机错误 未能连接到一个Windows服务

    windows 7 开机错误 未能连接到一个Windows服务Windows无法连接到systemeventnotificationservice服务。此问题阻止标准用户登录系统。作为管理员用户,您可以复查系统事件日志,以获得有关此服务未响应原因的详细信息。如下图:莫名其妙突然电脑死机了,重启后就出现了上述问题,并且电脑无法连网,开机速度慢到需要4分钟多,刚开机还黑屏。查看systemeventnotificationserv…

    2022年5月15日
    45

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号