WriteLog.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #region 模块信息
  2. // **********************************************************************
  3. // Copyright (C) 2019 jiamiantech
  4. // Please contact me if you have any questions
  5. // File Name: WriteLog
  6. // Author: 幻世界
  7. // WeChat||QQ: at853394528 || 853394528
  8. // **********************************************************************
  9. #endregion
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Text;
  16. using UnityEngine;
  17. using Debug = UnityEngine.Debug;
  18. public class WriteLog : MonoBehaviour
  19. {
  20. private static FileStream FileWriter;
  21. private static UTF8Encoding encoding;
  22. private static WriteLog consoleLog;
  23. private void Awake()
  24. {
  25. LogStart();
  26. }
  27. public static WriteLog ConsoleLog //开启单例
  28. {
  29. get
  30. {
  31. if (consoleLog == null)
  32. consoleLog = new WriteLog();
  33. return consoleLog;
  34. }
  35. }
  36. public void LogStart()
  37. {
  38. //Debug.LogError("开始写入日志");
  39. Directory.CreateDirectory(Application.persistentDataPath + "/Log");
  40. string NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(" ", "_").Replace("/", "_").Replace(":", "_");
  41. FileInfo fileInfo = new FileInfo(Application.persistentDataPath + "/Log/" + NowTime + "_Log.txt");
  42. //设置Log文件输出地址
  43. FileWriter = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  44. encoding = new UTF8Encoding();
  45. Application.logMessageReceived += LogCallback;
  46. Debug.LogError("开始写入日志");
  47. }
  48. /// <summary>
  49. /// Log回调
  50. /// </summary>
  51. /// <param name="condition">输出内容</param>
  52. /// <param name="stackTrace">堆栈追踪</param>
  53. /// <param name="type">Log日志类型</param>
  54. private void LogCallback(string condition, string stackTrace, LogType type) //写入控制台数据
  55. {
  56. //输出的日志类型可以自定义
  57. string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "【" + type + "】" + "【" + stackTrace + "】" + ":" + condition + Environment.NewLine + Environment.NewLine;
  58. FileWriter.Write(encoding.GetBytes(content), 0, encoding.GetByteCount(content));
  59. FileWriter.Flush();
  60. }
  61. private void OnDestroy()
  62. {
  63. }
  64. private void OnApplicationQuit()
  65. {
  66. //关闭写入
  67. if ((FileWriter != null))
  68. {
  69. Debug.LogError("日志写入结束");
  70. FileWriter.Close();
  71. Application.logMessageReceived -= LogCallback;
  72. }
  73. }
  74. }