FileLogger.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace VCommon.Logging
  9. {
  10. public class FileLogger : ILogger
  11. {
  12. // {logTo}\{level}\{level}_yyyyMMdd_{num:000}.log
  13. // [*]按时间创建
  14. // [*]续写
  15. // [*]按大小分卷
  16. // [*]自动删除旧文件
  17. public bool LogToConsole { get; set; }
  18. public int ByteSplit { get; }
  19. public int? PreserveDays { get; }
  20. public string LogTo { get; }
  21. protected enum Level
  22. {
  23. All,
  24. Debug,
  25. Trace,
  26. Info,
  27. Warn,
  28. Error,
  29. Fatal
  30. }
  31. private readonly Dictionary<Level, FileRoller> _rollers = new Dictionary<Level, FileRoller>();
  32. private readonly FileRoller _allRoller;
  33. private Task _cleanOldFileTask;
  34. private readonly Dictionary<string, DateTime> _files = new Dictionary<string, DateTime>();
  35. protected FileLogger(int mbSplit = 10, int? preserveDays = null, string logTo = null, bool enableAll = false)
  36. {
  37. //init env
  38. ByteSplit = mbSplit * 1024 * 1024;
  39. PreserveDays = preserveDays;
  40. LogTo = logTo ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  41. if (enableAll)
  42. _allRoller = new FileRoller(this, Level.All);
  43. if (PreserveDays.HasValue)
  44. {
  45. if (Directory.Exists(logTo))
  46. {
  47. var files = Directory.GetFiles(LogTo, "*.log", SearchOption.AllDirectories);
  48. foreach (var file in files)
  49. {
  50. var fn = Path.GetFileNameWithoutExtension(file)?.Split('_');
  51. if (fn?.Length == 3)
  52. {
  53. var dt = DateTime.ParseExact(fn[1], "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
  54. _files[file] = dt;
  55. }
  56. }
  57. CleanOldFiles();
  58. }
  59. }
  60. }
  61. private void NewFileCreated(string fullPath, DateTime dt)
  62. {
  63. if (!PreserveDays.HasValue) return;
  64. lock (_files)
  65. {
  66. _files[fullPath] = dt;
  67. }
  68. }
  69. private void CleanOldFiles()
  70. {
  71. if (false == PreserveDays.HasValue) return;
  72. if (false == _cleanOldFileTask?.IsCompleted) return;
  73. var timeToDelete = DateTime.Now.Date.AddDays(-PreserveDays.Value);
  74. _cleanOldFileTask = Task.Factory.StartNew(() =>
  75. {
  76. KeyValuePair<string, DateTime>[] files;
  77. lock (_files)
  78. {
  79. files = _files.ToArray();
  80. }
  81. var filesToDelete = files.Where(p => p.Value < timeToDelete).Select(p => p.Key);
  82. foreach (var file in filesToDelete)
  83. {
  84. File.Delete(file);
  85. lock (_files)
  86. {
  87. _files.Remove(file);
  88. }
  89. }
  90. });
  91. }
  92. private void WriteLogInternal(Level level, string summary, object moreInfo)
  93. {
  94. lock (this)
  95. {
  96. try
  97. {
  98. CleanOldFiles();
  99. if (!_rollers.TryGetValue(level, out var roller)) roller = _rollers[level] = new FileRoller(this, level);
  100. var today = DateTime.Now;
  101. var formatted = FormatMessage(today, level, summary, moreInfo);
  102. roller.WriteLine(today, formatted);
  103. _allRoller?.WriteLine(today, formatted);
  104. if (LogToConsole)
  105. {
  106. Console.WriteLine(formatted);
  107. }
  108. }
  109. catch (Exception e)
  110. {
  111. System.Diagnostics.Debug.Print(e.ToString());
  112. System.Diagnostics.Debug.Print(summary);
  113. }
  114. }
  115. }
  116. protected virtual string FormatMessage(DateTime time, Level level, string summary, object moreInfo)
  117. {
  118. return $"{time:yyyy-MM-dd HH:mm:ss.fff} {level} {summary} {moreInfo}";
  119. }
  120. public void Debug(string summary, object moreInfo = null)
  121. {
  122. WriteLogInternal(Level.Debug, summary, moreInfo);
  123. }
  124. public void Trace(string summary, object moreInfo = null)
  125. {
  126. WriteLogInternal(Level.Trace, summary, moreInfo);
  127. }
  128. public void Info(string summary, object moreInfo = null)
  129. {
  130. WriteLogInternal(Level.Info, summary, moreInfo);
  131. }
  132. public void Warn(string summary, object moreInfo = null)
  133. {
  134. WriteLogInternal(Level.Warn, summary, moreInfo);
  135. }
  136. public void Error(string summary, object moreInfo = null)
  137. {
  138. WriteLogInternal(Level.Error, summary, moreInfo);
  139. }
  140. public void Fatal(string summary, object moreInfo = null)
  141. {
  142. WriteLogInternal(Level.Fatal, summary, moreInfo);
  143. }
  144. private class FileRoller
  145. {
  146. private readonly FileLogger _ctx;
  147. private readonly Level _level;
  148. private DateTime _fsInstanceDate;
  149. private int _rollNum;
  150. private FileStream _fsInstance;
  151. public FileRoller(FileLogger ctx, Level level)
  152. {
  153. _level = level;
  154. _ctx = ctx;
  155. }
  156. private void SwitchFile()
  157. {
  158. _fsInstance?.Close();
  159. var fullPath = Path.Combine(_ctx.LogTo, _level.ToString(), $"{_level}_{_fsInstanceDate:yyyyMMdd}_{_rollNum:000}.log");
  160. _fsInstance = File.Open(fullPath, FileMode.Append, FileAccess.Write, FileShare.Read);
  161. _ctx.NewFileCreated(fullPath, _fsInstanceDate);
  162. }
  163. private void EnsureFsInstance(DateTime dateTime)
  164. {
  165. var date = dateTime.Date;
  166. if (null != _fsInstance && _fsInstanceDate == date) return;
  167. _fsInstanceDate = date;
  168. //ensure dir
  169. var path = Path.Combine(_ctx.LogTo, _level.ToString());
  170. if (false == Directory.Exists(path)) Directory.CreateDirectory(path);
  171. //find last file or start from 0
  172. var pattern = $"{_level}_{_fsInstanceDate:yyyyMMdd}_???.log";
  173. var lastFile = Directory.GetFiles(path, pattern).OrderByDescending(p => p).FirstOrDefault();
  174. _rollNum = null != lastFile
  175. ? int.Parse(Path.GetFileNameWithoutExtension(lastFile).Split('_').Last())
  176. : 0;
  177. SwitchFile();
  178. }
  179. private void RollNext()
  180. {
  181. _rollNum++;
  182. SwitchFile();
  183. }
  184. public void WriteLine(DateTime date, string content)
  185. {
  186. EnsureFsInstance(date);
  187. var buf = Encoding.UTF8.GetBytes(content + Environment.NewLine);
  188. if (_fsInstance.Length + buf.Length > _ctx.ByteSplit) RollNext();
  189. _fsInstance.Write(buf, 0, buf.Length);
  190. _fsInstance.Flush();
  191. }
  192. }
  193. }
  194. }