LogManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using static System.DateTime;
  10. namespace Masuit.Tools.Logging
  11. {
  12. /// <summary>
  13. /// 日志组件
  14. /// </summary>
  15. public class LogManager
  16. {
  17. static readonly ConcurrentQueue<Tuple<string, string>> LogQueue = new ConcurrentQueue<Tuple<string, string>>();
  18. public static event Action<string> Event;
  19. static LogManager()
  20. {
  21. var writeTask = new Task(obj =>
  22. {
  23. while (true)
  24. {
  25. Pause.WaitOne(1000, true);
  26. List<string[]> temp = new List<string[]>();
  27. foreach (var logItem in LogQueue)
  28. {
  29. string logPath = logItem.Item1;
  30. Event?.Invoke(logItem.Item2);
  31. string logMergeContent = String.Concat(logItem.Item2, Environment.NewLine, "----------------------------------------------------------------------------------------------------------------------", Environment.NewLine);
  32. string[] logArr = temp.FirstOrDefault(d => d[0].Equals(logPath));
  33. if (logArr != null)
  34. {
  35. logArr[1] = string.Concat(logArr[1], logMergeContent);
  36. }
  37. else
  38. {
  39. logArr = new[] { logPath, logMergeContent };
  40. temp.Add(logArr);
  41. }
  42. LogQueue.TryDequeue(out Tuple<string, string> _);
  43. }
  44. foreach (var item in temp)
  45. {
  46. WriteText(item[0], item[1]);
  47. }
  48. }
  49. }, null, TaskCreationOptions.LongRunning);
  50. writeTask.Start();
  51. }
  52. private static AutoResetEvent Pause => new AutoResetEvent(false);
  53. /// <summary>
  54. /// 日志存放目录,默认日志放在当前应用程序运行目录下的logs文件夹中
  55. /// </summary>
  56. public static string LogDirectory { get; set; } = Path.Combine(AppContext.BaseDirectory, "Logs");
  57. /// <summary>
  58. /// 写入Info级别的日志
  59. /// </summary>
  60. /// <param name="info"></param>
  61. public static void Info(string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {info}"));
  62. /// <summary>
  63. /// 写入Info级别的日志
  64. /// </summary>
  65. /// <param name="source"></param>
  66. /// <param name="info"></param>
  67. public static void Info(string source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source} {info}"));
  68. /// <summary>
  69. /// 写入Info级别的日志
  70. /// </summary>
  71. /// <param name="source"></param>
  72. /// <param name="info"></param>
  73. public static void Info(Type source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source.FullName} {info}"));
  74. /// <summary>
  75. /// 写入debug级别日志
  76. /// </summary>
  77. /// <param name="debug">异常对象</param>
  78. public static void Debug(string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {debug}"));
  79. /// <summary>
  80. /// 写入debug级别日志
  81. /// </summary>
  82. /// <param name="source">异常源的类型</param>
  83. /// <param name="debug">异常对象</param>
  84. public static void Debug(string source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source} {debug}"));
  85. /// <summary>
  86. /// 写入debug级别日志
  87. /// </summary>
  88. /// <param name="source">异常源的类型</param>
  89. /// <param name="debug">异常对象</param>
  90. public static void Debug(Type source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source.FullName} {debug}"));
  91. /// <summary>
  92. /// 写入error级别日志
  93. /// </summary>
  94. /// <param name="error">异常对象</param>
  95. public static void Error(Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {error.Source} {error.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {error.Source} {error.StackTrace}"));
  96. /// <summary>
  97. /// 写入error级别日志
  98. /// </summary>
  99. /// <param name="source">异常源的类型</param>
  100. /// <param name="error">异常对象</param>
  101. public static void Error(Type source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error.StackTrace}"));
  102. /// <summary>
  103. /// 写入error级别日志
  104. /// </summary>
  105. /// <param name="source">异常源的类型</param>
  106. /// <param name="error">异常信息</param>
  107. public static void Error(Type source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error}"));
  108. /// <summary>
  109. /// 写入error级别日志
  110. /// </summary>
  111. /// <param name="source">异常源的类型</param>
  112. /// <param name="error">异常对象</param>
  113. public static void Error(string source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error.StackTrace}"));
  114. /// <summary>
  115. /// 写入error级别日志
  116. /// </summary>
  117. /// <param name="source">异常源的类型</param>
  118. /// <param name="error">异常信息</param>
  119. public static void Error(string source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error}"));
  120. /// <summary>
  121. /// 写入fatal级别日志
  122. /// </summary>
  123. /// <param name="fatal">异常对象</param>
  124. public static void Fatal(Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {fatal.Source} {fatal.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {fatal.Source} {fatal.StackTrace}"));
  125. /// <summary>
  126. /// 写入fatal级别日志
  127. /// </summary>
  128. /// <param name="source">异常源的类型</param>
  129. /// <param name="fatal">异常对象</param>
  130. public static void Fatal(Type source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal.StackTrace}"));
  131. /// <summary>
  132. /// 写入fatal级别日志
  133. /// </summary>
  134. /// <param name="source">异常源的类型</param>
  135. /// <param name="fatal">异常对象</param>
  136. public static void Fatal(Type source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal}"));
  137. /// <summary>
  138. /// 写入fatal级别日志
  139. /// </summary>
  140. /// <param name="source">异常源的类型</param>
  141. /// <param name="fatal">异常对象</param>
  142. public static void Fatal(string source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal.Message}{Environment.NewLine}{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal.StackTrace}"));
  143. /// <summary>
  144. /// 写入fatal级别日志
  145. /// </summary>
  146. /// <param name="source">异常源的类型</param>
  147. /// <param name="fatal">异常对象</param>
  148. public static void Fatal(string source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal}"));
  149. private static string GetLogPath()
  150. {
  151. string newFilePath;
  152. String logDir = string.IsNullOrEmpty(LogDirectory) ? Path.Combine(Environment.CurrentDirectory, "logs") : LogDirectory;
  153. if (!Directory.Exists(logDir))
  154. {
  155. Directory.CreateDirectory(logDir);
  156. }
  157. string extension = ".log";
  158. string fileNameNotExt = String.Concat(Now.ToString("yyyyMMdd"));
  159. string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
  160. List<string> filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList();
  161. if (filePaths.Count > 0)
  162. {
  163. int fileMaxLen = filePaths.Max(d => d.Length);
  164. string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault();
  165. if (new FileInfo(lastFilePath).Length > 1 * 1024 * 1024)
  166. {
  167. string no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value;
  168. bool parse = int.TryParse(no, out int tempno);
  169. string formatno = $"({(parse ? (tempno + 1) : tempno)})";
  170. string newFileName = String.Concat(fileNameNotExt, formatno, extension);
  171. newFilePath = Path.Combine(logDir, newFileName);
  172. }
  173. else
  174. {
  175. newFilePath = lastFilePath;
  176. }
  177. }
  178. else
  179. {
  180. string newFileName = string.Concat(fileNameNotExt, $"({0})", extension);
  181. newFilePath = Path.Combine(logDir, newFileName);
  182. }
  183. return newFilePath;
  184. }
  185. private static void WriteText(string logPath, string logContent)
  186. {
  187. try
  188. {
  189. if (!File.Exists(logPath))
  190. {
  191. File.CreateText(logPath).Close();
  192. }
  193. using (StreamWriter sw = File.AppendText(logPath))
  194. {
  195. Event(logContent);
  196. sw.Write(logContent);
  197. }
  198. }
  199. catch (Exception)
  200. {
  201. }
  202. }
  203. }
  204. }