Unity Log管理(一) 一件关闭 重新定位

https://blog.csdn.net/qq_26999509/article/details/78516237
在开发中我们为了查看错误 或者某些信息会用的Debug或者断点
而且有时候我们会为了调试方便添加一些工具 方便调试

了解一下原理

https://blog.csdn.net/qq_42351033/article/details/83990499
这个是print和log的区别

image.png

但是这个发布时候又不需要 log也会消耗挺大一部分内存和GC
在playersetting中有三个选项


image.png

然鹅这个None不是不打印
这个是从左到右依次的结果


image.png

可以看出参数还是传递了
这是正常的
image.png

看之前很多封装了一堆的log类,因为是老版本吧 现在unity很多自带都有
这一句话可以直接关闭log输出

Debug.unityLogger.logEnabled = false;

直接不消耗了


image.png

怎样发布能看见呢
这个是控制日记文本存在不存在


image.png

这个日志路径是在
C:\Users\Administrator\AppData\LocalLow\DefaultCompany(公司名)\EventCenter(项目名)

跟控制台输出差不多不过有点看的难受


image.png
image.png

这个不用可以不勾


image.png

然后都勾上


image.png

exe运行时会有提示
image.png

然后你的Debug.LogError 会在这里


image.png

还能直接打开那个写入文件的位置
这个不是滑块
然后log LogWarning 都不会显示
我们就自己要做一个 在那之前我们把Log类简单改一改

/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   overrideDebug
 *History:
*/

public class Debug
{
    const string logColor = "white";
    const string errorColor = "red";
    const string warningColor = "yellow";

    public static void Log(string msg)
    {
        UnityEngine.Debug.Log(GetColor(msg, logColor));
    }

    public static void LogError(string msg)
    {
        UnityEngine.Debug.LogError(GetColor(msg, errorColor));
    }

    public static void LogWarning(string msg)
    {
        UnityEngine.Debug.LogWarning(GetColor(msg, warningColor));
    }

    static string GetColor(string msg, string color)
    {
        return $"<color={color}>{msg}</color>";
    }
}

是不是更明显了


image.png

但是双击跳转时候就完蛋了 跑这里了


image.png

所以还要写自定义的函数
这个是定义特性Conditional标签
image.png

这样就是不编译 方法调用也不存在


image.png

你要保证你的代码没有BUG
/**
*Copyright(C) 2019 by #COMPANY#
*All rights reserved.
*FileName:     #SCRIPTFULLNAME#
*Author:       #AUTHOR#
*Version:      #VERSION#
*UnityVersion:#UNITYVERSION#
*Date:         #DATE#
*Description:   overrideDebug
*History:
*/
using System.Diagnostics;
public class Debug
{
    const string logColor = "white";
    const string errorColor = "red";
    const string warningColor = "yellow";

    //Conditional("LOG")]
    public static void Log(string msg)
    {
        UnityEngine.Debug.Log(GetColor(msg, logColor));
    }

    //Conditional("LOG")]
    public static void LogError(string msg)
    {
        UnityEngine.Debug.LogError(GetColor(msg, errorColor));
    }

    //Conditional("LOG")]
    public static void LogWarning(string msg)
    {
        UnityEngine.Debug.LogWarning(GetColor(msg, warningColor));
    }

    static string GetColor(string msg, string color)
    {
        return $"<color={color}>{msg}</color>";
    }
}

然后再每个方法上面加上一段迷之注释
用这个Editor可以进行调用的转换
这个replace 一个是string 的可能是字符串太多没有 还有个是Regex.Replace 静态方法也没用
最后只有这个正则表达式有用 本来想直接替换掉整个不要这个奇怪的注释
然而[]是正则表达式的一个公式吧 用了@/]限制不住最后一个不转义
然后又试过插入一行 不过没有这个功能..
就只能这样了 期待大家有什么好方法
这个还有个坑 替换进去的时候[是不能加@的

/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   
 *History:
*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
public class DebugSetting
{
    readonly static string Debug_Path = $"{Application.dataPath}/Debug.cs";

    [MenuItem("Tools/ChangeDebugOff")]
    static void DebugOff()
    {
        PlayerSettings.usePlayerLog = false;
        ChangeDebug(false);
    }

    [MenuItem("Tools/ChangeDebugOn")]
    static void DebugOn()
    {
        PlayerSettings.usePlayerLog = true;
        ChangeDebug(true);
    }

    static void ChangeDebug(bool isOn)
    {
        string files = FileTools.ReadFileString(Debug_Path);
        if (isOn)
        {
            Regex r = new Regex(@"\[");
            files = r.Replace(files, "//");
        }
        else
        { 
            Regex r = new Regex("//");
            files = r.Replace(files, "[");
        }


        FileTools.CreateFileString(Debug_Path, files);
    }
}

然后就是Log跳转了

Log重新定向

https://blog.csdn.net/qq_37776196/article/details/85324348

 [OnOpenAsset(0)]
    static bool OnOpenAsset(int instanceID, int line)
    {
        var statckTrack = GetStackTrace();
        var fileNames = statckTrack?.Split('\n');

        return false;
    }

    static string GetStackTrace()
    {
        //UnityEditor.ConsoleWindow
        var consoleWndType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
        //找到成员
        var fieldInfo = consoleWndType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
        var consoleWnd = fieldInfo.GetValue(null);
        if (consoleWnd == null)
            return "";
        //// 如果console窗口时焦点窗口的话,获取stacktrace
        if ((object)consoleWnd == EditorWindow.focusedWindow)
        {
            fieldInfo = consoleWndType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
            return fieldInfo.GetValue(consoleWnd).ToString();
        }
        return "";
    }
image.png

然后我我们通过反射然后字符串截取得到了就是console面板一样信息的字符串
我们要得到的是


image.png

找了一下规律我们要的类有at 然后是并且不是我们自己定义的Debug类
FileTools 是我之前写的IO读写类 还有字符串截取扩展方法 可以自行用别的方法替换

/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   
 *History:
*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEditor.Callbacks;
using System.Reflection;

public class DebugSetting
{
    readonly static string Debug_Path = $"{Application.dataPath}/Debug.cs";

    [MenuItem("Tools/ChangeDebug/Off", false, 0)]
    static void DebugOff()
    {
        PlayerSettings.usePlayerLog = false;
        ChangeDebug(false);
    }

    [MenuItem("Tools/ChangeDebug/On", false, 0)]
    static void DebugOn()
    {
        PlayerSettings.usePlayerLog = true;
        ChangeDebug(true);
    }

    /// <summary>
    ///更改特性
    /// </summary>
    /// <param name="isOn"></param>
    static void ChangeDebug(bool isOn)
    {
        string files = FileTools.ReadFileString(Debug_Path);
        if (isOn)
        {
            Regex r = new Regex(@"\[");
            files = r.Replace(files, "//");
        }
        else
        {
            Regex r = new Regex("//");
            files = r.Replace(files, "[");
        }

        FileTools.CreateFileString(Debug_Path, files);
    }

    [OnOpenAsset(-1)]
    static bool OnOpenAsset(int instanceID, int line)
    {
       
        var statckTrack = GetStackTrace();
        var fileNames = statckTrack?.Split('\n');
        for (int i = 0; i < fileNames.Length; i++)
        {
            if (fileNames[i].IndexOf("at")!=-1&&fileNames[i].IndexOf("Debug:Log")==-1)
            {               
                //从两个字符串中间取得路径 并去除空格
                var classPath = fileNames[i].GetLimitStr("at", ":").Replace(" ","");
                var logLine= fileNames[i].GetLimitStr(":", ")").ToInt();                
                AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath<Object>(classPath), logLine);
                return true;                          
            }         
        }
        return false;
    }

    static string GetStackTrace()
    {
        //UnityEditor.ConsoleWindow
        var consoleWndType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
        //找到成员
        var fieldInfo = consoleWndType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
        var consoleWnd = fieldInfo.GetValue(null);
        if (consoleWnd == null)
            return "";
        //// 如果console窗口时焦点窗口的话,获取stacktrace
        if ((object)consoleWnd == EditorWindow.focusedWindow)
        {
            fieldInfo = consoleWndType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
            return fieldInfo.GetValue(consoleWnd).ToString();
        }
        return "";
    }




}

然后写完堆栈溢出了


image.png

有人说PlayerSetting .Net版本从3.5到4.6就行了
我重启编辑器就好了


image.png

点击了永远是3 没错就是第三个
image.png

在外面Debug也没问题


image.png

这就很尴尬了
一直卡这里出不去了
image.png

我把循环提取出来 不是循环的问题
就是这一条 不解除注释就不会堆栈溢出
image.png

然后缩小范围到这一句
image.png

没错是这个方法有问题
然后打断点发现这个方法整个就都在一直进循环进
最终我换了个方法不会堆栈溢出了
可能是.NET我是4.X的原因吧 按道理VS2017 .NET应该都有4.6
我的有点奇怪啊 而且用2019.1.9也是最高这个版本


image.png
/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   
 *History:
*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEditor.Callbacks;
using System.Reflection;
using UnityEditorInternal;

public class DebugSetting
{
    readonly static string Debug_Path = $"{Application.dataPath}/Debug.cs";

    [MenuItem("Tools/ChangeDebug/Off", false, 0)]
    static void DebugOff()
    {
        PlayerSettings.usePlayerLog = false;
        ChangeDebug(false);
    }

    [MenuItem("Tools/ChangeDebug/On", false, 0)]
    static void DebugOn()
    {
        PlayerSettings.usePlayerLog = true;
        ChangeDebug(true);
    }

    /// <summary>
    ///更改特性
    /// </summary>
    /// <param name="isOn"></param>
    static void ChangeDebug(bool isOn)
    {
        string files = FileTools.ReadFileString(Debug_Path);
        if (isOn)
        {
            Regex r = new Regex(@"\[");
            files = r.Replace(files, "//");
        }
        else
        {
            Regex r = new Regex("//");
            files = r.Replace(files, "[");
        }

        FileTools.CreateFileString(Debug_Path, files);
    }

    [OnOpenAsset(-1)]
    static bool OnOpenAsset(int instanceID, int line)
    {
       
        var statckTrack = GetStackTrace();
        var fileNames = statckTrack?.Split('\n');
        for (int i = 0; i < fileNames.Length; i++)
        {   
            if (fileNames[i].IndexOf("at")!=-1&&fileNames[i].IndexOf("Debug:Log")==-1)
            {               
                //从两个字符串中间取得路径 并去除空格 再去除多余Assets
                var classPath = fileNames[i].GetLimitStr("at", ":").Replace(" ","").Replace("Assets","");
                var logLine= fileNames[i].GetLimitStr(":", ")").ToInt();

                InternalEditorUtility.OpenFileAtLineExternal(Application.dataPath+ classPath, logLine);
                return true;                          
            }
           
        }
        return false;
    }


    static string GetStackTrace()
    {
        //UnityEditor.ConsoleWindow
        var consoleWndType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
        //找到成员
        var fieldInfo = consoleWndType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
        var consoleWnd = fieldInfo.GetValue(null);
        if (consoleWnd == null)
            return "";
        //// 如果console窗口时焦点窗口的话,获取stacktrace
        if ((object)consoleWnd == EditorWindow.focusedWindow)
        {
            fieldInfo = consoleWndType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
            return fieldInfo.GetValue(consoleWnd).ToString();
        }
        return "";
    }




}

然后我发现这里可以更新

然后是有个问题
跳转 update 有个 at 还有多个:无法识别的问题


image.png
/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   
 *History:
*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEditor.Callbacks;
using System.Reflection;
using UnityEditorInternal;

public class DebugSetting
{
    readonly static string Debug_Path = $"{Application.dataPath}/Debug.cs";

    [MenuItem("Tools/ChangeDebug/Off", false, 0)]
    static void DebugOff()
    {
        PlayerSettings.usePlayerLog = false;
        ChangeDebug(false);
    }

    [MenuItem("Tools/ChangeDebug/On", false, 0)]
    static void DebugOn()
    {
        PlayerSettings.usePlayerLog = true;
        ChangeDebug(true);
    }

    /// <summary>
    ///更改特性
    /// </summary>
    /// <param name="isOn"></param>
    static void ChangeDebug(bool isOn)
    {
        string files = FileTools.ReadFileString(Debug_Path);
        if (isOn)
        {
            Regex r = new Regex(@"\[");
            files = r.Replace(files, "//");
        }
        else
        {
            Regex r = new Regex("//");
            files = r.Replace(files, "[");
        }

        FileTools.CreateFileString(Debug_Path, files);
    }

    [OnOpenAsset(-1)]
    static bool OnOpenAsset(int instanceID, int line)
    {
       
        var statckTrack = GetStackTrace();
        var fileNames = statckTrack?.Split('\n');
        for (int i = 0; i < fileNames.Length; i++)
        {   
            if (fileNames[i].IndexOf("at")!=-1&&fileNames[i].IndexOf("Debug:Log")==-1)
            {               
                //从两个字符串中间取得路径 并去除空格 再去除多余Assets
                var classPath = fileNames[i].GetLimitStr("(at", ":").Replace(" ","").Replace("Assets","");
                var logLine= fileNames[i].GetLimitStr(":", ")").ToInt();

                InternalEditorUtility.OpenFileAtLineExternal(Application.dataPath+ classPath, logLine);
                return true;                          
            }
           
        }
        return false;
    }


    static string GetStackTrace()
    {
        //UnityEditor.ConsoleWindow
        var consoleWndType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
        //找到成员
        var fieldInfo = consoleWndType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
        var consoleWnd = fieldInfo.GetValue(null);
        if (consoleWnd == null)
            return "";
        //// 如果console窗口时焦点窗口的话,获取stacktrace
        if ((object)consoleWnd == EditorWindow.focusedWindow)
        {
            fieldInfo = consoleWndType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
            return fieldInfo.GetValue(consoleWnd).ToString();
        }
        return "";
    }




}
/**
 *Copyright(C) 2019 by #COMPANY#
 *All rights reserved.
 *FileName:     #SCRIPTFULLNAME#
 *Author:       #AUTHOR#
 *Version:      #VERSION#
 *UnityVersion:#UNITYVERSION#
 *Date:         #DATE#
 *Description:   
 *History:
*/
using System;
using System.Text;
/// <summary>
/// String扩展方法
/// </summary>
public static class SubString
{
    /// <summary>
    /// 获取某个限定之后的字符串 如果限定存在多个则取最后一个的位置
    /// </summary>
    public static string GetAfterKeyData(this string str, string key)
    {
        int index = str.LastIndexOf(key) + key.Length;
        int length = str.Length - index;
        return str.Substring(index, length);
    }
    /// <summary>
    /// 获取某个限定之前的字符串 如果限定存在多个则取最后一个的位置
    /// </summary>
    public static string GetBeforeKeyData(this string str, string key)
    {
        int index = str.LastIndexOf(key);
        return str.Substring(0, index);
    }
    /// <summary>
    /// 获取限定范围内的字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="star"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    public static string GetLimitStr(this string str, string star, string end)
    {
        if (star.IndexOf(end, 0) != -1)
            return "";
        //转换为在字符串第几位
        int i = str.LastIndexOf(star);
        //第二个与第一个index差值
        int j = str.LastIndexOf(end);
        if (i == -1 || j == -1)
            return "";
        //截取的位置就是第一个位置加上他的长度 到 第二个位置与第一个位置的差值
        return str.Substring(i + star.Length, j - i - star.Length);
    }


    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }

    /// <summary>
    /// 支持负数转换
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static int ToInt(this string str)
    {
        return str.Contains("-") ? -int.Parse(str.Replace("-", "")) : int.Parse(str);
    }

    /// <summary>
    /// 字符串相加优化用于大循环
    /// </summary>
    /// <param name="str"></param>
    /// <param name="callBack"></param>
    /// <returns></returns>
    public static string StrBuild(this string str, Action<StringBuilder> callBack)
    {
        StringBuilder sb = new StringBuilder(str);
        callBack?.Invoke(sb);
        return sb.ToString();
    }
}

这样就好了 寻找两个关键词之间的字符串 只识别最后一个关键字
寻找at 改为(at就不会重复了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容