• Unity Debug的简单封装


    Unity Debug的简单封装

    使用前提:
    Project Settings-Player-Other Settings-Script Define Symbols添加 EnableLog,点击Apply
    在这里插入图片描述

    测试代码:

    using MTools.Debuger;
    using UnityEngine;
    
    public class NewBehaviourScript : MonoBehaviour
    {
        public string TAGNAME = "我是日志的标签";
    
        void Start()
        {
            Debuger.LogLevel = LogLevel.Error;  //测试,项目中可以通过读取配置文件,更改日志级别
    
            Debuger.Info("我是一个测试");
            Debuger.Info("NewBehaviourScript", "我是一个测试");
            Debuger.Warn("我是一个测试");
            Debuger.Warn("NewBehaviourScript", "我是一个测试");
            Debuger.Error("我是一个测试");
            Debuger.Error("NewBehaviourScript", "我是一个测试");
    
            this.Info("我是一个测试2");
            this.Warn("我是一个测试2");
            this.Error("我是一个测试2");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    效果图:
    在这里插入图片描述
    日志封装类
    Debuger.cs

    using System;
    using System.IO;
    using System.Diagnostics;
    using UnityEngine;
    
    namespace MTools.Debuger
    {
        /// 
        /// 日志级别
        /// 
        public enum LogLevel : byte
        {
            /// 
            /// 信息级别
            /// 
            Info,
    
            /// 
            /// 警告级别
            /// 
            Warn,
    
            /// 
            /// 错误级别
            /// 
            Error
        }
    
        public class Debuger
        {
            /// 
            /// 日志级别(默认Info)
            /// 
            public static LogLevel LogLevel = LogLevel.Info;
            /// 
            /// 是否使用Unity打印
            /// 
            public static bool UseUnityEngine = true;
            /// 
            /// 是否显示时间
            /// 
            public static bool EnableTime = false;
            /// 
            /// 是否显示堆栈信息
            /// 
            public static bool EnableStack = false;
            /// 
            /// 是否保存到文本
            /// 
            public static bool EnableSave = false;
            /// 
            /// 打印文本流
            /// 
            public static StreamWriter LogFileWriter = null;
            /// 
            /// 日志保存路径(文件夹)
            /// 
            public static string LogFileDir = "";
            /// 
            /// 日志文件名
            /// 
            public static string LogFileName = "";
    
            //打印格式: {0}-时间 {1}-标签/类名/TAGNAME字段值 {2}-内容
            private static string InfoFormat = "[Info] {0}{1} {2}";
            private static string WarnFormat = "[Warn] {0}{1} {2}";
            private static string ErrorFormat = "[Error] {0}{1} {2}";
    
            private static void Internal_Log(string msg, object context = null)
            {
                bool useUnityEngine = UseUnityEngine;
                if (useUnityEngine)
                {
                    UnityEngine.Debug.Log(msg, (UnityEngine.Object)context);
                }
                else
                {
                    Console.WriteLine(msg);
                }
            }
    
            private static void Internal_Warn(string msg, object context = null)
            {
                bool useUnityEngine = UseUnityEngine;
                if (useUnityEngine)
                {
                    UnityEngine.Debug.LogWarning(msg, (UnityEngine.Object)context);
                }
                else
                {
                    Console.WriteLine(msg);
                }
            }
    
            private static void Internal_Error(string msg, object context = null)
            {
                bool useUnityEngine = UseUnityEngine;
                if (useUnityEngine)
                {
                    UnityEngine.Debug.LogError(msg, (UnityEngine.Object)context);
                }
                else
                {
                    Console.WriteLine(msg);
                }
            }
    
            #region Info
            [Conditional("EnableLog")]
            public static void Info(object message)
            {
                if (LogLevel >= LogLevel.Info)
                {
                    string msg = string.Format(InfoFormat, GetLogTime(), "", message);
                    Internal_Log(msg, null);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Info(object message, object context)
            {
                if (LogLevel >= LogLevel.Info)
                {
                    string msg = string.Format(InfoFormat, GetLogTime(), "", message);
                    Internal_Log(msg, context);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Info(string tag, string message)
            {
                if (LogLevel >= LogLevel.Info)
                {
                    string msg = string.Format(InfoFormat, GetLogTime(), tag, message);
                    Internal_Log(msg, null);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Info(string tag, string format, params object[] args)
            {
                if (LogLevel >= LogLevel.Info)
                {
                    string msg = string.Format(format, args);
                    msg = string.Format(InfoFormat, GetLogTime(), tag, msg);
                    Internal_Log(msg, null);
                    WriteToFile(msg, false);
                }
            }
            #endregion
    
            #region Warn
            [Conditional("EnableLog")]
            public static void Warn(object message)
            {
                if (LogLevel >= LogLevel.Warn)
                {
                    string msg = string.Format(WarnFormat, GetLogTime(), "", message);
                    Internal_Warn(msg, null);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Warn(object message, object context)
            {
                if (LogLevel >= LogLevel.Warn)
                {
                    string msg = string.Format(WarnFormat, GetLogTime(), "", message);
                    Internal_Warn(msg, context);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Warn(string tag, string message)
            {
                if (LogLevel >= LogLevel.Warn)
                {
                    string msg = string.Format(WarnFormat, GetLogTime(), tag, message);
                    Internal_Warn(msg, null);
                    WriteToFile(msg, false);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Warn(string tag, string format, params object[] args)
            {
                if (LogLevel >= LogLevel.Warn)
                {
                    string msg = string.Format(format, args);
                    msg = string.Format(WarnFormat, GetLogTime(), tag, msg);
                    Internal_Warn(msg, null);
                    WriteToFile(msg, false);
                }
            }
            #endregion
    
            #region Error
            [Conditional("EnableLog")]
            public static void Error(object message)
            {
                if (LogLevel >= LogLevel.Error)
                {
                    string msg = string.Format(ErrorFormat, GetLogTime(), "", message);
                    Internal_Error(msg, null);
                    WriteToFile(msg, true);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Error(object message, object context)
            {
                if (LogLevel >= LogLevel.Error)
                {
                    string msg = string.Format(ErrorFormat, GetLogTime(), "", message);
                    Internal_Error(msg, context);
                    WriteToFile(msg, true);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Error(string tag, string message)
            {
                if (LogLevel >= LogLevel.Error)
                {
                    string msg = string.Format(ErrorFormat, GetLogTime(), tag, message);
                    Internal_Error(msg, null);
                    WriteToFile(msg, true);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Error(string tag, string format, params object[] args)
            {
                if (LogLevel >= LogLevel.Error)
                {
                    string msg = string.Format(format, args);
                    msg = string.Format(ErrorFormat, GetLogTime(), tag, msg);
                    Internal_Error(msg, null);
                    WriteToFile(msg, true);
                }
            }
            #endregion
    
            /// 
            /// 获取时间
            /// 
            /// 
            private static string GetLogTime()
            {
                string result = "";
                if (EnableTime)
                {
                    result = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " ";
                }
                return result;
            }
    
            /// 
            /// 序列化打印信息
            /// 
            /// 打印信息
            /// 是否开启堆栈打印
            private static void WriteToFile(string message, bool EnableStack = false)
            {
                bool flag = !EnableSave;
                if (!flag)
                {
                    bool flag2 = LogFileWriter == null;
                    if (flag2)
                    {
                        LogFileName = DateTime.Now.GetDateTimeFormats('s')[0].ToString();
                        LogFileName = LogFileName.Replace("-", "_");
                        LogFileName = LogFileName.Replace(":", "_");
                        LogFileName = LogFileName.Replace(" ", "");
                        LogFileName += ".log";
                        bool flag3 = string.IsNullOrEmpty(LogFileDir);
                        if (flag3)
                        {
                            try
                            {
                                bool useUnityEngine = UseUnityEngine;
                                if (useUnityEngine)
                                {
                                    LogFileDir = Application.persistentDataPath + "/DebugerLog/";
                                }
                                else
                                {
                                    string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                                    LogFileDir = baseDirectory + "/DebugerLog/";
                                }
                            }
                            catch (Exception ex)
                            {
                                string msg = string.Format(ErrorFormat, "", "", "获取 Application.persistentDataPath 报错!" + ex.Message);
                                Internal_Error(msg, null);
                                return;
                            }
                        }
                        string path = LogFileDir + LogFileName;
                        try
                        {
                            bool flag4 = !Directory.Exists(LogFileDir);
                            if (flag4)
                            {
                                Directory.CreateDirectory(LogFileDir);
                            }
                            LogFileWriter = File.AppendText(path);
                            LogFileWriter.AutoFlush = true;
                        }
                        catch (Exception ex2)
                        {
                            LogFileWriter = null;
                            string msg = string.Format(ErrorFormat, "", "", "LogToCache()" + ex2.Message + ex2.StackTrace);
                            Internal_Error(msg, null);
                            return;
                        }
                    }
                    bool flag5 = LogFileWriter != null;
                    if (flag5)
                    {
                        try
                        {
                            LogFileWriter.WriteLine(message);
                            bool flag6 = (EnableStack || Debuger.EnableStack) && UseUnityEngine;
                            if (flag6)
                            {
                                LogFileWriter.WriteLine(StackTraceUtility.ExtractStackTrace());
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342

    日志扩展类
    DebugerExtension.cs

    using System.Reflection;
    using System.Diagnostics;
    
    namespace MTools.Debuger
    {
        /// 
        /// 自定义Debuger类的扩展类
        /// 
        public static class DebugerExtension
        {
            [Conditional("EnableLog")]
            public static void Info(this object obj, string message)
            {
                if (Debuger.LogLevel >= LogLevel.Info)
                {
                    Debuger.Info(GetLogTag(obj), message);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Info(this object obj, string format, params object[] args)
            {
                if (Debuger.LogLevel >= LogLevel.Info)
                {
                    string message = string.Format(format, args);
                    Debuger.Info(GetLogTag(obj), message);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Warning(this object obj, string message)
            {
                if (Debuger.LogLevel >= LogLevel.Warn)
                {
                    Debuger.Warn(GetLogTag(obj), message);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Warn(this object obj, string format, params object[] args)
            {
                if (Debuger.LogLevel >= LogLevel.Warn)
                {
                    string message = string.Format(format, args);
                    Debuger.Warn(GetLogTag(obj), message);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Error(this object obj, string message)
            {
                if (Debuger.LogLevel >= LogLevel.Error)
                {
                    Debuger.Error(GetLogTag(obj), message);
                }
            }
    
            [Conditional("EnableLog")]
            public static void Error(this object obj, string format, params object[] args)
            {
                if (Debuger.LogLevel >= LogLevel.Error)
                {
                    string message = string.Format(format, args);
                    Debuger.Error(GetLogTag(obj), message);
                }
            }
            /// 
            /// 获取调用打印的类名称或者标记有TAGNAME的字段
            /// 有TAGNAME字段的,触发类名称用TAGNAME字段对应的赋值
            /// 没有用类的名称代替
            /// 
            /// 触发Log对应的类
            /// 
            private static string GetLogTag(object obj)
            {
                FieldInfo field = obj.GetType().GetField("TAGNAME");
                bool flag = field != null;
                string result;
                if (flag)
                {
                    result = (string)field.GetValue(obj);
                }
                else
                {
                    result = obj.GetType().Name;
                }
                return result;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90

    日志拦截器, 实现Unity中Console窗口双击跳转到合理的位置
    LogIntercepter.cs

    using System;
    using System.Reflection;
    using UnityEditor;
    using UnityEditor.Callbacks;
    using UnityEngine;
    
    namespace M.Editor
    {
        /// 
        /// 日志拦截器
        /// 
        internal sealed class LogIntercepter
        {
            private static LogIntercepter _current;
            private static LogIntercepter Current
            {
                get
                {
                    if (_current == null)
                    {
                        _current = new LogIntercepter();
                    }
                    return _current;
                }
            }
    
            private Type _consoleWindowType;
            private FieldInfo _activeTextInfo;
            private FieldInfo _consoleWindowInfo;
            private MethodInfo _setActiveEntry;
            private object[] _setActiveEntryArgs;
            private object _consoleWindow;
    
            private LogIntercepter()
            {
                _consoleWindowType = Type.GetType("UnityEditor.ConsoleWindow,UnityEditor");
                _activeTextInfo = _consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
                _consoleWindowInfo = _consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
                _setActiveEntry = _consoleWindowType.GetMethod("SetActiveEntry", BindingFlags.Instance | BindingFlags.NonPublic);
                _setActiveEntryArgs = new object[] { null };
            }
    
            [OnOpenAsset]
            private static bool OnOpenAsset(int instanceID, int line)
            {
                UnityEngine.Object instance = EditorUtility.InstanceIDToObject(instanceID);
                if (AssetDatabase.GetAssetOrScenePath(instance).EndsWith(".cs"))
                {
                    return Current.OpenAsset();//双击会触发这里
                }
                return false;
            }
    
            private bool OpenAsset()
            {
                string stackTrace = GetStackTrace();
                if (stackTrace != "")
                {
                    //结合条件  可以用来过滤是否使用了原始接口还是自定义的
                    if (stackTrace.Contains("[Info]") || stackTrace.Contains("[Warn]") || stackTrace.Contains("[Error]"))
                    {
                        string[] paths = stackTrace.Split('\n');
    
                        for (int i = 0; i < paths.Length; i++)
                        {
                            //过滤日志封装类和日志扩展类
                            if (!paths[i].Contains("Debuger.cs") && !paths[i].Contains("DebugerExtension.cs") && paths[i].Contains(" (at "))
                            {
                                return OpenScriptAsset(paths[i]);
                            }
                        }
                    }
                }
                return false;
            }
    
            private bool OpenScriptAsset(string path)
            {
                int startIndex = path.IndexOf(" (at ") + 5;
                int endIndex = path.IndexOf(".cs:") + 3;
                string filePath = path.Substring(startIndex, endIndex - startIndex);
                string lineStr = path.Substring(endIndex + 1, path.Length - endIndex - 2);
                TextAsset asset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath);
                if (asset != null)
                {
                    int line;
                    if (int.TryParse(lineStr, out line))
                    {
                        object consoleWindow = GetConsoleWindow();
                        _setActiveEntry.Invoke(consoleWindow, _setActiveEntryArgs);
    
                        EditorGUIUtility.PingObject(asset);
                        AssetDatabase.OpenAsset(asset, line);
                        return true;
                    }
                }
                return false;
            }
    
            private string GetStackTrace()
            {
                object consoleWindow = GetConsoleWindow();
    
                if (consoleWindow != null)
                {
                    if (consoleWindow == EditorWindow.focusedWindow as object)
                    {
                        object value = _activeTextInfo.GetValue(consoleWindow);
                        return value != null ? value.ToString() : "";
                    }
                }
                return "";
            }
    
            private object GetConsoleWindow()
            {
                if (_consoleWindow == null)
                {
                    _consoleWindow = _consoleWindowInfo.GetValue(null);
                }
                return _consoleWindow;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
  • 相关阅读:
    基于Python计算PLS中的VIP值(变量投影重要性分析法)
    MyBatis(二、基础进阶)
    项目实战第十七讲:使用异步编排优化商品详情页(对外流量最大)
    JAVA毕业设计购物网站设计计算机源码+lw文档+系统+调试部署+数据库
    Jmeter 之 “查看结果树” 界面功能介绍
    《对比Excel,轻松学习Python数据分析》读书笔记------时间序列
    jQuery网页开发案例:jQuery常用API--jQuery 尺寸、位置操作及 电梯导航案例和节流阀(互斥锁)
    程序设计原则
    还原试卷的软件叫什么?这3款一键还原
    私域电商:实体商家想通过异业联盟引流,应该怎么做?
  • 原文地址:https://blog.csdn.net/weixin_44238530/article/details/128155664