Unity 游戏框架搭建 (八) 减少加班利器-QLog

为毛要实现这个工具?

在我小时候,每当游戏到了测试阶段,交给 QA 测试, QA 测试了一会儿拿着设备过来说游戏闪退了。。。。当我拿到设备后测了好久 Bug 也没有复现,排查了好久也没有头绪,就算接了 Bugly 拿到的也只是闪退的异常信息,或者干脆拿不到。很抓狂,因为这个我是没少加班。所以当时想着解决下这个小小的痛点。。。

现在框架中的QLog:

怎么用呢?在初始化的地方调用这句话就够了。

  1. QLog.Instance ();

其实做成单例也没有必要。。。。

日志获取方法:

PC端或者Mac端,日志存放在工程的如下位置:8.减少加班利器-QLog - 图1打开之后是这样的:8.减少加班利器-QLog - 图2最后一条信息是触发了一个空指针异常,堆栈信息一目了然。如果是iOS端,需要使用类似同步推或者iTools工具获取日志文件,路径是这样的:8.减少加班利器-QLog - 图3Android端的话,类似的方式,但是具体路径没查过,不好意思。。。

初版

一开始想做一个保存 Debug.Log、Debug.LogWaring、Debug.LogError 信息奥本地文件的小工具。上网一查原来有大神实现了,贴上链接:http://www.xuanyusong.com/archives/2477。其思路是使用 Application.RegisterLocCallback 注册回调,每次使用 Debug.Log 等 API 时候会触发一次回调,在回调中将Log信息保存在本地。而且意外的发现,Application.RegisterLogCallback 也能接收到异常和错误信息。所以将这份实现作为 QLog 的初版用了一段时间,发现存在一个问题,如果游戏发生闪退,好多 Log 信息没来得及存到本地,因为刷入到本地操作是通过 Update 完成的,每帧之间的间隔,其实很长。

现在的版本:

后来找到了一份实现,思路和初版一样区别是将Update改成线程来刷。Application.RegisterLogCallback 这时候已经弃用了,改成了 Application.logMessageReceived,后来又找到了 Application.logMessageReceivedThreaded。如果只是使用 Application.logMessageReceived 的时候,在真机上如果发生 Error 或者 Exception 时,收不到堆栈信息。但是使用了 Application.logMessageReceivedThreaded 就可以接收到堆栈信息了,不过在处理 Log 信息的时候要保证线程安全。

说明部分就这些吧,实现起来其实没什么难点,主要就是好好利用 Application.logMessageReceived 和 Application.logMessageReceivedThreaded 这两个API就好了。

下面贴上我的框架中的实现,这里要注意一下,这份实现依赖于上篇文章介绍的App类(已经重命名为QApp了)。接口类ILogOutput:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace QFramework

  6. {
  7. ///
  8. /// 日志输出接口
  9. ///
  10. public interface ILogOutput
  11. {
  12. ///
  13. /// 输出日志数据
  14. ///
  15. /// 日志数据
  16. void Log(QLog.LogData logData);
  17. ///
  18. /// 关闭
  19. ///
  20. void Close();
  21. }
  22. }

接口实现类 QFileLogOutput

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.IO;
  6. using UnityEngine;

  7. namespace QFramework

  8. {
  9. ///
  10. /// 文本日志输出
  11. ///
  12. public class QFileLogOutput : ILogOutput
  13. {

  14. if UNITY_EDITOR

  15. string mDevicePersistentPath = Application.dataPath + “/../PersistentPath”;
  16. elif UNITY_STANDALONE_WIN

  17. string mDevicePersistentPath = Application.dataPath + “/PersistentPath”;
  18. elif UNITY_STANDALONE_OSX

  19. string mDevicePersistentPath = Application.dataPath + “/PersistentPath”;
  20. else

  21. string mDevicePersistentPath = Application.persistentDataPath;
  22. endif

  23. static string LogPath = “Log”;

  24. private Queue mWritingLogQueue = null;

  25. private Queue mWaitingLogQueue = null;
  26. private object mLogLock = null;
  27. private Thread mFileLogThread = null;
  28. private bool mIsRunning = false;
  29. private StreamWriter mLogWriter = null;

  30. public QFileLogOutput()

  31. {
  32. QApp.Instance().onApplicationQuit += Close;
  33. this.mWritingLogQueue = new Queue();
  34. this.mWaitingLogQueue = new Queue();
  35. this.mLogLock = new object();
  36. System.DateTime now = System.DateTime.Now;
  37. string logName = string.Format(“Q{0}{1}{2}{3}{4}{5}”,
  38. now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
  39. string logPath = string.Format(“{0}/{1}/{2}.txt”, mDevicePersistentPath, LogPath, logName);
  40. if (File.Exists(logPath))
  41. File.Delete(logPath);
  42. string logDir = Path.GetDirectoryName(logPath);
  43. if (!Directory.Exists(logDir))
  44. Directory.CreateDirectory(logDir);
  45. this.mLogWriter = new StreamWriter(logPath);
  46. this.mLogWriter.AutoFlush = true;
  47. this.mIsRunning = true;
  48. this.mFileLogThread = new Thread(new ThreadStart(WriteLog));
  49. this.mFileLogThread.Start();
  50. }

  51. void WriteLog()

  52. {
  53. while (this.mIsRunning)
  54. {
  55. if (this.mWritingLogQueue.Count == 0)
  56. {
  57. lock (this.mLogLock)
  58. {
  59. while (this.mWaitingLogQueue.Count == 0)
  60. Monitor.Wait(this.mLogLock);
  61. Queue tmpQueue = this.mWritingLogQueue;
  62. this.mWritingLogQueue = this.mWaitingLogQueue;
  63. this.mWaitingLogQueue = tmpQueue;
  64. }
  65. }
  66. else
  67. {
  68. while (this.mWritingLogQueue.Count > 0)
  69. {
  70. QLog.LogData log = this.mWritingLogQueue.Dequeue();
  71. if (log.Level == QLog.LogLevel.ERROR)
  72. {
  73. this.mLogWriter.WriteLine(“——————————————————————————————————————————————————————————-“);
  74. this.mLogWriter.WriteLine(System.DateTime.Now.ToString() + “\t” + log.Log + “\n”);
  75. this.mLogWriter.WriteLine(log.Track);
  76. this.mLogWriter.WriteLine(“——————————————————————————————————————————————————————————-“);
  77. }
  78. else
  79. {
  80. this.mLogWriter.WriteLine(System.DateTime.Now.ToString() + “\t” + log.Log);
  81. }
  82. }
  83. }
  84. }
  85. }

  86. public void Log(QLog.LogData logData)

  87. {
  88. lock (this.mLogLock)
  89. {
  90. this.mWaitingLogQueue.Enqueue(logData);
  91. Monitor.Pulse(this.mLogLock);
  92. }
  93. }

  94. public void Close()

  95. {
  96. this.mIsRunning = false;
  97. this.mLogWriter.Close();
  98. }
  99. }
  100. }

QLog类

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Text;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. namespace QFramework {
  7. ///
  8. /// 封装日志模块
  9. ///
  10. public class QLog : QSingleton
  11. {
  12. ///
  13. /// 日志等级,为不同输出配置用
  14. ///
  15. public enum LogLevel
  16. {
  17. LOG = 0,
  18. WARNING = 1,
  19. ASSERT = 2,
  20. ERROR = 3,
  21. MAX = 4,
  22. }

  23. ///

  24. /// 日志数据类
  25. ///
  26. public class LogData
  27. {
  28. public string Log { get; set; }
  29. public string Track { get; set; }
  30. public LogLevel Level { get; set; }
  31. }

  32. ///

  33. /// OnGUI回调
  34. ///
  35. public delegate void OnGUICallback();

  36. ///

  37. /// UI输出日志等级,只要大于等于这个级别的日志,都会输出到屏幕
  38. ///
  39. public LogLevel uiOutputLogLevel = LogLevel.LOG;
  40. ///
  41. /// 文本输出日志等级,只要大于等于这个级别的日志,都会输出到文本
  42. ///
  43. public LogLevel fileOutputLogLevel = LogLevel.MAX;
  44. ///
  45. /// unity日志和日志输出等级的映射
  46. ///
  47. private Dictionary logTypeLevelDict = null;
  48. ///
  49. /// OnGUI回调
  50. ///
  51. public OnGUICallback onGUICallback = null;
  52. ///
  53. /// 日志输出列表
  54. ///
  55. private List logOutputList = null;
  56. private int mainThreadID = -1;

  57. ///

  58. /// Unity的Debug.Assert()在发布版本有问题
  59. ///
  60. /// 条件
  61. /// 输出信息
  62. public static void Assert(bool condition, string info)
  63. {
  64. if (condition)
  65. return;
  66. Debug.LogError(info);
  67. }

  68. private QLog()

  69. {
  70. Application.logMessageReceived += LogCallback;
  71. Application.logMessageReceivedThreaded += LogMultiThreadCallback;

  72. this.logTypeLevelDict = new Dictionary

  73. {
  74. { LogType.Log, LogLevel.LOG },
  75. { LogType.Warning, LogLevel.WARNING },
  76. { LogType.Assert, LogLevel.ASSERT },
  77. { LogType.Error, LogLevel.ERROR },
  78. { LogType.Exception, LogLevel.ERROR },
  79. };

  80. this.uiOutputLogLevel = LogLevel.LOG;

  81. this.fileOutputLogLevel = LogLevel.ERROR;
  82. this.mainThreadID = Thread.CurrentThread.ManagedThreadId;
  83. this.logOutputList = new List
  84. {
  85. new QFileLogOutput(),
  86. };

  87. QApp.Instance().onGUI += OnGUI;

  88. QApp.Instance().onDestroy += OnDestroy;
  89. }

  90. void OnGUI()

  91. {
  92. if (this.onGUICallback != null)
  93. this.onGUICallback();
  94. }

  95. void OnDestroy()

  96. {
  97. Application.logMessageReceived -= LogCallback;
  98. Application.logMessageReceivedThreaded -= LogMultiThreadCallback;
  99. }

  100. ///

  101. /// 日志调用回调,主线程和其他线程都会回调这个函数,在其中根据配置输出日志
  102. ///
  103. /// 日志
  104. /// 堆栈追踪
  105. /// 日志类型
  106. void LogCallback(string log, string track, LogType type)
  107. {
  108. if (this.mainThreadID == Thread.CurrentThread.ManagedThreadId)
  109. Output(log, track, type);
  110. }

  111. void LogMultiThreadCallback(string log, string track, LogType type)

  112. {
  113. if (this.mainThreadID != Thread.CurrentThread.ManagedThreadId)
  114. Output(log, track, type);
  115. }

  116. void Output(string log, string track, LogType type)

  117. {
  118. LogLevel level = this.logTypeLevelDict[type];
  119. LogData logData = new LogData
  120. {
  121. Log = log,
  122. Track = track,
  123. Level = level,
  124. };
  125. for (int i = 0; i < this.logOutputList.Count; ++i)
  126. this.logOutputList[i].Log(logData);
  127. }
  128. }
  129. }

欢迎讨论!

相关链接:

我的框架地址:https://github.com/liangxiegame/QFramework

教程源码:https://github.com/liangxiegame/QFramework/tree/master/Assets/HowToWriteUnityGameFramework/

QFramework &游戏框架搭建QQ交流群: 623597263

转载请注明地址:凉鞋的笔记http://liangxiegame.com/

微信公众号:liangxiegame

8.减少加班利器-QLog - 图4

如果有帮助到您:

如果觉得本篇教程对您有帮助,不妨通过以下方式赞助笔者一下,鼓励笔者继续写出更多高质量的教程,也让更多的力量加入 QFramework 。