XLog.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace XCharts.Runtime
  8. {
  9. /// <summary>
  10. /// Log system. Used to output logs with date and log type, support output to file, support custom output log type.
  11. /// ||日志系统。用于输出带日期和日志类型的日志,支持输出到文件,支持自定义输出的日志类型。
  12. /// </summary>
  13. public class XLog : MonoBehaviour
  14. {
  15. public const int ALL = 0;
  16. public const int WARNING = 1;
  17. public const int DEBUG = 2;
  18. public const int INFO = 3;
  19. public const int PROTO = 4;
  20. public const int VITAL = 5;
  21. public const int ERROR = 6;
  22. public const int EXCEPTION = 7;
  23. private const int MAX_ERROR_LOG = 20;
  24. public static bool isReportBug = false;
  25. public static bool isOutputLog = false;
  26. public static bool isUploadLog = false;
  27. public static bool isCloseOutLog = false;
  28. public static int errorCount = 0;
  29. public static int exceptCount = 0;
  30. public static int uploadTick = 20;
  31. public static int reportTick = 10;
  32. private static bool initFileSuccess = false;
  33. private static bool[] levelList = new bool[] { true, true, true, true, true, true, true, true };
  34. private static List<string> writeList = new List<string>();
  35. private static float uploadTime = 0;
  36. private static float reportTime = 0;
  37. private string outpath;
  38. private StreamWriter writer;
  39. private string[] temp;
  40. public int logCount = 0;
  41. public static List<string> errorList = new List<string>();
  42. private static object m_Lock = new object();
  43. private static XLog m_Instance;
  44. public static XLog Instance
  45. {
  46. get
  47. {
  48. // if (m_Instance == null)
  49. // {
  50. // GameObject go = new GameObject("XLog");
  51. // m_Instance = go.AddComponent<XLog>();
  52. // DontDestroyOnLoad(go);
  53. // }
  54. return m_Instance;
  55. }
  56. }
  57. void Awake()
  58. {
  59. if (m_Instance != null)
  60. {
  61. Destroy(gameObject);
  62. return;
  63. }
  64. m_Instance = this;
  65. InitLogFile();
  66. // Application.logMessageReceived += HandleLog;
  67. Application.logMessageReceivedThreaded += HandleLog;
  68. }
  69. void OnDestroy()
  70. {
  71. if (writer != null)
  72. {
  73. writer.Close();
  74. writer.Dispose();
  75. }
  76. // Application.logMessageReceived -= HandleLog;
  77. Application.logMessageReceivedThreaded -= HandleLog;
  78. }
  79. void Update()
  80. {
  81. uploadTime += Time.deltaTime;
  82. reportTime += Time.deltaTime;
  83. lock (m_Lock)
  84. {
  85. if (writeList.Count > 0)
  86. {
  87. logCount = writeList.Count;
  88. if (!initFileSuccess)
  89. {
  90. writeList.Clear();
  91. return;
  92. }
  93. try
  94. {
  95. temp = writeList.ToArray();
  96. int count = 0;
  97. foreach (var str in temp)
  98. {
  99. count++;
  100. writer.WriteLine(str);
  101. writeList.Remove(str);
  102. if (count > 10) break;
  103. }
  104. writer.Flush();
  105. }
  106. catch (Exception e)
  107. {
  108. initFileSuccess = false;
  109. //Application.logMessageReceived -= HandleLog;
  110. Application.logMessageReceivedThreaded -= HandleLog;
  111. UnityEngine.Debug.LogError("write outlog.txt error:" + e.Message);
  112. }
  113. }
  114. }
  115. }
  116. private void InitLogFile()
  117. {
  118. ClearAllLog();
  119. XLog.EnableLog(ALL);
  120. if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
  121. {
  122. XLog.ClearAllLog();
  123. XLog.EnableLog(VITAL);
  124. XLog.EnableLog(ERROR);
  125. XLog.isReportBug = true;
  126. XLog.isUploadLog = true;
  127. }
  128. else
  129. {
  130. XLog.isUploadLog = false;
  131. XLog.isReportBug = false;
  132. }
  133. outpath = GetLogOutputPath();
  134. try
  135. {
  136. if (File.Exists(outpath))
  137. {
  138. File.Delete(outpath);
  139. }
  140. writer = new StreamWriter(outpath, false, Encoding.UTF8);
  141. writer.WriteLine(GetNowTime() + "init file success!!");
  142. UnityEngine.Debug.Log(GetNowTime() + "init file success:" + outpath);
  143. writer.Flush();
  144. initFileSuccess = true;
  145. }
  146. catch (Exception e)
  147. {
  148. initFileSuccess = false;
  149. Application.logMessageReceived -= HandleLog;
  150. UnityEngine.Debug.LogError("write outlog.txt error:" + e.Message);
  151. }
  152. }
  153. private static string GetLogOutputPath()
  154. {
  155. #if UNITY_EDITOR
  156. string path = Application.dataPath + "/../outlog.txt";
  157. #else
  158. string path = Application.persistentDataPath + "/outlog.txt";
  159. if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
  160. {
  161. path = Application.persistentDataPath + "/outlog.txt";
  162. }
  163. else
  164. {
  165. path = Application.dataPath + "/../outlog.txt";
  166. }
  167. #endif
  168. return path;
  169. }
  170. private void HandleLog(string logString, string stackTrace, LogType type)
  171. {
  172. lock (m_Lock)
  173. {
  174. if (!initFileSuccess) return;
  175. int index = logString.IndexOf("stack traceback");
  176. if (index > 0)
  177. {
  178. string log = logString.Substring(0, index);
  179. string trace = logString.Substring(index, logString.Length - index);
  180. logString = log;
  181. stackTrace = trace;
  182. }
  183. if (type == LogType.Log)
  184. {
  185. }
  186. else if (type == LogType.Error)
  187. {
  188. if (logString.IndexOf("LUA ERROR") > 0 || logString.IndexOf("stack traceback") > 0) exceptCount++;
  189. else errorCount++;
  190. writeList.Add(logString);
  191. //writeList.Add(stackTrace + "\n");
  192. if (errorList.Count >= MAX_ERROR_LOG)
  193. {
  194. errorList.RemoveAt(1);
  195. }
  196. if (errorList.Count < MAX_ERROR_LOG)
  197. {
  198. errorList.Add(logString);
  199. // errorList.Add(stackTrace + "\n");
  200. }
  201. }
  202. else if (type == LogType.Exception)
  203. {
  204. exceptCount++;
  205. writeList.Add(logString);
  206. writeList.Add(stackTrace + "\n");
  207. if (errorList.Count >= MAX_ERROR_LOG)
  208. {
  209. errorList.RemoveAt(1);
  210. }
  211. if (errorList.Count < MAX_ERROR_LOG)
  212. {
  213. errorList.Add(logString);
  214. errorList.Add(stackTrace + "\n");
  215. }
  216. }
  217. }
  218. }
  219. public static void FlushLog()
  220. {
  221. var instance = XLog.Instance;
  222. if (instance != null && instance.writer != null)
  223. {
  224. for (int i = 0; i < writeList.Count; i++)
  225. {
  226. instance.writer.WriteLine(writeList[i]);
  227. }
  228. instance.writer.Flush();
  229. writeList.Clear();
  230. }
  231. }
  232. public static void EnableLog(int logType)
  233. {
  234. if (logType < 0 || logType >= levelList.Length) return;
  235. levelList[logType] = true;
  236. }
  237. public static void ClearAllLog()
  238. {
  239. for (int i = 0; i < levelList.Length; i++)
  240. {
  241. levelList[i] = false;
  242. }
  243. }
  244. public static bool CanLog(int level)
  245. {
  246. if (level < 0 || level >= levelList.Length) return false;
  247. return levelList[level] || levelList[0];
  248. }
  249. public static void Log(string log)
  250. {
  251. Debug(log);
  252. }
  253. public static void LogError(string log)
  254. {
  255. Error(log);
  256. }
  257. public static void LogWarning(string log)
  258. {
  259. Warning(log);
  260. }
  261. public static void Debug(string log)
  262. {
  263. if (!CanLog(DEBUG)) return;
  264. UnityEngine.Debug.Log(GetNowTime() + "[DEBUG]\t" + log);
  265. }
  266. public static void Vital(string log)
  267. {
  268. if (!CanLog(INFO)) return;
  269. UnityEngine.Debug.Log(GetNowTime() + "[VITAL]\t" + log);
  270. }
  271. public static void Info(string log)
  272. {
  273. if (!CanLog(INFO)) return;
  274. UnityEngine.Debug.Log(GetNowTime() + "[INFO]\t" + log);
  275. }
  276. public static void Proto(string log)
  277. {
  278. if (!CanLog(PROTO)) return;
  279. UnityEngine.Debug.Log(GetNowTime() + "[PROTO]\t" + log);
  280. }
  281. public static void Warning(string log)
  282. {
  283. if (!CanLog(WARNING)) return;
  284. UnityEngine.Debug.LogWarning(GetNowTime() + "[WARN]\t" + log);
  285. }
  286. public static void Error(string log)
  287. {
  288. if (!CanLog(ERROR)) return;
  289. UnityEngine.Debug.LogError(GetNowTime() + "[ERROR]\t" + log);
  290. }
  291. public static string GetNowTime(string formatter = null)
  292. {
  293. DateTime now = DateTime.Now;
  294. if (formatter == null)
  295. return now.ToString("[HH:mm:ss fff]", DateTimeFormatInfo.InvariantInfo);
  296. else
  297. return now.ToString(formatter, DateTimeFormatInfo.InvariantInfo);
  298. }
  299. public static ulong GetTimestamp()
  300. {
  301. return (ulong)(DateTime.Now - new DateTime(190, 1, 1, 0, 0, 0, 0)).TotalSeconds;
  302. }
  303. }
  304. }