WriteLog.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. public static WriteLog ConsoleLog //开启单例
  24. {
  25. get
  26. {
  27. if (consoleLog == null)
  28. consoleLog = new WriteLog();
  29. return consoleLog;
  30. }
  31. }
  32. private void Start()
  33. {
  34. #if UNITY_EDITOR
  35. LogStart();
  36. #endif
  37. }
  38. public void LogStart()
  39. {
  40. //Debug.LogError("开始写入日志");
  41. Directory.CreateDirectory(Application.persistentDataPath + "/Log");
  42. string NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(" ", "_").Replace("/", "_").Replace(":", "_");
  43. FileInfo fileInfo = new FileInfo(Application.persistentDataPath + "/Log/" + NowTime + "_Log.txt");
  44. //设置Log文件输出地址
  45. FileWriter = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  46. encoding = new UTF8Encoding();
  47. Application.logMessageReceived += LogCallback;
  48. Debug.LogError("开始写入日志");
  49. }
  50. /// <summary>
  51. /// Log回调
  52. /// </summary>
  53. /// <param name="condition">输出内容</param>
  54. /// <param name="stackTrace">堆栈追踪</param>
  55. /// <param name="type">Log日志类型</param>
  56. private void LogCallback(string condition, string stackTrace, LogType type) //写入控制台数据
  57. {
  58. //输出的日志类型可以自定义
  59. string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "【" + type + "】" + "【" + stackTrace + "】" + ":" + condition + Environment.NewLine + Environment.NewLine;
  60. FileWriter.Write(encoding.GetBytes(content), 0, encoding.GetByteCount(content));
  61. FileWriter.Flush();
  62. }
  63. private void OnDestroy()
  64. {
  65. }
  66. private void OnApplicationQuit()
  67. {
  68. #if UNITY_EDITOR
  69. //关闭写入
  70. if ((FileWriter != null))
  71. {
  72. Debug.LogError("日志写入结束");
  73. FileWriter.Close();
  74. Application.logMessageReceived -= LogCallback;
  75. }
  76. #endif
  77. }
  78. }