LogWriter.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. namespace XGame.Framework.Logger
  5. {
  6. internal class LogWriter : ILogWriter, IDisposable
  7. {
  8. private LogType _logType;
  9. private MMFile _mmfile;
  10. private ILogCompressor _compressor;
  11. public object _syncRoot;
  12. private object SyncRoot
  13. {
  14. get
  15. {
  16. if (this._syncRoot == null)
  17. {
  18. //如果_syncRoot和null相等,将new object赋值给 _syncRoot
  19. //Interlocked.CompareExchange方法保证多个线程在使用 syncRoot时是线程安全的
  20. Interlocked.CompareExchange(ref this._syncRoot, new object(), null);
  21. }
  22. return this._syncRoot;
  23. }
  24. }
  25. public LogWriter(LogType logType, MMFile mmfile, ILogCompressor compressor)
  26. {
  27. _logType = logType;
  28. _mmfile = mmfile;
  29. _compressor = compressor;
  30. }
  31. #region 接口实现
  32. public void Write(string contents)
  33. {
  34. lock (this.SyncRoot)
  35. {
  36. contents += '\n';
  37. var buffer = System.Text.Encoding.UTF8.GetBytes(contents);
  38. WriteToCache(buffer, 0, buffer.Length);
  39. }
  40. }
  41. public void Flush()
  42. {
  43. lock (this.SyncRoot)
  44. {
  45. WriteToFile();
  46. _mmfile.Reset();
  47. }
  48. }
  49. public void Dispose()
  50. {
  51. _mmfile.Dispose();
  52. _mmfile = null;
  53. }
  54. #endregion
  55. private void WriteToFile()
  56. {
  57. try
  58. {
  59. var header = _mmfile.ReadHeader();
  60. if (header.position <= 0) return;
  61. var buffer = _mmfile.ReadAll();
  62. if (_compressor != null)
  63. {
  64. buffer = _compressor.Compress(buffer);
  65. }
  66. // 每次写入的时候都进行判断文件夹是否存在
  67. var dirPath = GetLogDirectory();
  68. var logFilePath = $"{dirPath}/{DateTime.UtcNow}{LogDefine.FileExtension}";
  69. File.WriteAllBytes(logFilePath, buffer);
  70. }
  71. catch (Exception ex)
  72. {
  73. UnityEngine.Debug.LogException(ex);
  74. }
  75. }
  76. private void WriteToCache(byte[] buffer, int offset, int length)
  77. {
  78. try
  79. {
  80. if (!_mmfile.Write(buffer, offset, length))
  81. {
  82. WriteToFile();
  83. _mmfile.Reset();
  84. WriteToCache(buffer, offset, length);
  85. }
  86. }
  87. catch (Exception ex)
  88. {
  89. UnityEngine.Debug.LogException(ex);
  90. }
  91. }
  92. private string GetLogDirectory()
  93. {
  94. var dirPath = _logType == LogType.Code ? LogDefine.CodeLogPath : LogDefine.EventLogPath;
  95. if (!Directory.Exists(dirPath))
  96. {
  97. Directory.CreateDirectory(dirPath);
  98. }
  99. return dirPath;
  100. }
  101. }
  102. }