LogManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. private static readonly ConcurrentQueue<(string logPath, string msg)> LogQueue = new();
  18. /// <summary>
  19. /// 自定义事件
  20. /// </summary>
  21. public static event Action<LogInfo> Event;
  22. static LogManager()
  23. {
  24. Task.Factory.StartNew(() =>
  25. {
  26. while (true)
  27. {
  28. Pause.WaitOne(1000, true);
  29. var temp = new List<string[]>();
  30. foreach (var (logPath, msg) in LogQueue)
  31. {
  32. var logMergeContent = string.Concat(msg, Environment.NewLine, "----------------------------------------------------------------------------------------------------------------------", Environment.NewLine);
  33. var logArr = temp.FirstOrDefault(d => d[0].Equals(logPath));
  34. if (logArr != null)
  35. {
  36. logArr[1] = string.Concat(logArr[1], logMergeContent);
  37. }
  38. else
  39. {
  40. logArr = new[]
  41. {
  42. logPath,
  43. logMergeContent
  44. };
  45. temp.Add(logArr);
  46. }
  47. LogQueue.TryDequeue(out _);
  48. }
  49. foreach (var item in temp)
  50. {
  51. WriteText(item[0], item[1]);
  52. }
  53. }
  54. }, TaskCreationOptions.LongRunning);
  55. }
  56. private static AutoResetEvent Pause => new AutoResetEvent(false);
  57. private static string _logDirectory;
  58. /// <summary>
  59. /// 日志存放目录,默认日志放在当前应用程序运行目录下的logs文件夹中
  60. /// </summary>
  61. public static string LogDirectory
  62. {
  63. get => _logDirectory ?? (Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).Any(s => s.Contains("Web.config")) ? AppDomain.CurrentDomain.BaseDirectory + @"App_Data\Logs\" : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"));
  64. set
  65. {
  66. //自定义目录
  67. if (!Directory.Exists(value))
  68. {
  69. Directory.CreateDirectory(value);
  70. }
  71. _logDirectory = value;
  72. }
  73. }
  74. /// <summary>
  75. /// 写入Info级别的日志
  76. /// </summary>
  77. /// <param name="info"></param>
  78. public static void Info(string info)
  79. {
  80. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {info}"));
  81. var log = new LogInfo()
  82. {
  83. LogLevel = LogLevel.Info,
  84. Message = info,
  85. Time = Now,
  86. ThreadId = Thread.CurrentThread.ManagedThreadId
  87. };
  88. Event?.Invoke(log);
  89. }
  90. /// <summary>
  91. /// 写入Info级别的日志
  92. /// </summary>
  93. /// <param name="source"></param>
  94. /// <param name="info"></param>
  95. public static void Info(string source, string info)
  96. {
  97. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source} {info}"));
  98. LogInfo log = new LogInfo()
  99. {
  100. LogLevel = LogLevel.Info,
  101. Message = info,
  102. Time = Now,
  103. ThreadId = Thread.CurrentThread.ManagedThreadId,
  104. Source = source
  105. };
  106. Event?.Invoke(log);
  107. }
  108. /// <summary>
  109. /// 写入Info级别的日志
  110. /// </summary>
  111. /// <param name="source"></param>
  112. /// <param name="info"></param>
  113. public static void Info(Type source, string info)
  114. {
  115. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source.FullName} {info}"));
  116. LogInfo log = new LogInfo()
  117. {
  118. LogLevel = LogLevel.Info,
  119. Message = info,
  120. Time = Now,
  121. ThreadId = Thread.CurrentThread.ManagedThreadId,
  122. Source = source.FullName
  123. };
  124. Event?.Invoke(log);
  125. }
  126. /// <summary>
  127. /// 写入debug级别日志
  128. /// </summary>
  129. /// <param name="debug">异常对象</param>
  130. public static void Debug(string debug)
  131. {
  132. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {debug}"));
  133. LogInfo log = new LogInfo()
  134. {
  135. LogLevel = LogLevel.Debug,
  136. Message = debug,
  137. Time = Now,
  138. ThreadId = Thread.CurrentThread.ManagedThreadId
  139. };
  140. Event?.Invoke(log);
  141. }
  142. /// <summary>
  143. /// 写入debug级别日志
  144. /// </summary>
  145. /// <param name="source">异常源的类型</param>
  146. /// <param name="debug">异常对象</param>
  147. public static void Debug(string source, string debug)
  148. {
  149. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source} {debug}"));
  150. LogInfo log = new LogInfo()
  151. {
  152. LogLevel = LogLevel.Debug,
  153. Message = debug,
  154. Time = Now,
  155. ThreadId = Thread.CurrentThread.ManagedThreadId,
  156. Source = source
  157. };
  158. Event?.Invoke(log);
  159. }
  160. /// <summary>
  161. /// 写入debug级别日志
  162. /// </summary>
  163. /// <param name="source">异常源的类型</param>
  164. /// <param name="debug">异常对象</param>
  165. public static void Debug(Type source, string debug)
  166. {
  167. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source.FullName} {debug}"));
  168. LogInfo log = new LogInfo()
  169. {
  170. LogLevel = LogLevel.Debug,
  171. Message = debug,
  172. Time = Now,
  173. ThreadId = Thread.CurrentThread.ManagedThreadId,
  174. Source = source.FullName
  175. };
  176. Event?.Invoke(log);
  177. }
  178. /// <summary>
  179. /// 写入error级别日志
  180. /// </summary>
  181. /// <param name="error">异常对象</param>
  182. public static void Error(Exception error)
  183. {
  184. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {error.Source} {error.Message}{Environment.NewLine}{error.StackTrace}"));
  185. LogInfo log = new LogInfo()
  186. {
  187. LogLevel = LogLevel.Error,
  188. Message = error.Message,
  189. Time = Now,
  190. ThreadId = Thread.CurrentThread.ManagedThreadId,
  191. Source = error.Source,
  192. Exception = error,
  193. ExceptionType = error.GetType().Name
  194. };
  195. Event?.Invoke(log);
  196. }
  197. /// <summary>
  198. /// 写入error级别日志
  199. /// </summary>
  200. /// <param name="source">异常源的类型</param>
  201. /// <param name="error">异常对象</param>
  202. public static void Error(Type source, Exception error)
  203. {
  204. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error.Message}{Environment.NewLine}{error.StackTrace}"));
  205. LogInfo log = new LogInfo()
  206. {
  207. LogLevel = LogLevel.Error,
  208. Message = error.Message,
  209. Time = Now,
  210. ThreadId = Thread.CurrentThread.ManagedThreadId,
  211. Source = source.FullName,
  212. Exception = error,
  213. ExceptionType = error.GetType().Name
  214. };
  215. Event?.Invoke(log);
  216. }
  217. /// <summary>
  218. /// 写入error级别日志
  219. /// </summary>
  220. /// <param name="source">异常源的类型</param>
  221. /// <param name="error">异常信息</param>
  222. public static void Error(Type source, string error)
  223. {
  224. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error}"));
  225. LogInfo log = new LogInfo()
  226. {
  227. LogLevel = LogLevel.Error,
  228. Message = error,
  229. Time = Now,
  230. ThreadId = Thread.CurrentThread.ManagedThreadId,
  231. Source = source.FullName,
  232. //Exception = error,
  233. ExceptionType = error.GetType().Name
  234. };
  235. Event?.Invoke(log);
  236. }
  237. /// <summary>
  238. /// 写入error级别日志
  239. /// </summary>
  240. /// <param name="source">异常源的类型</param>
  241. /// <param name="error">异常对象</param>
  242. public static void Error(string source, Exception error)
  243. {
  244. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error.Message}{Environment.NewLine}{error.StackTrace}"));
  245. LogInfo log = new LogInfo()
  246. {
  247. LogLevel = LogLevel.Error,
  248. Message = error.Message,
  249. Time = Now,
  250. ThreadId = Thread.CurrentThread.ManagedThreadId,
  251. Source = source,
  252. Exception = error,
  253. ExceptionType = error.GetType().Name
  254. };
  255. Event?.Invoke(log);
  256. }
  257. /// <summary>
  258. /// 写入error级别日志
  259. /// </summary>
  260. /// <param name="source">异常源的类型</param>
  261. /// <param name="error">异常信息</param>
  262. public static void Error(string source, string error)
  263. {
  264. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error}"));
  265. LogInfo log = new LogInfo()
  266. {
  267. LogLevel = LogLevel.Error,
  268. Message = error,
  269. Time = Now,
  270. ThreadId = Thread.CurrentThread.ManagedThreadId,
  271. Source = source,
  272. //Exception = error,
  273. ExceptionType = error.GetType().Name
  274. };
  275. Event?.Invoke(log);
  276. }
  277. /// <summary>
  278. /// 写入fatal级别日志
  279. /// </summary>
  280. /// <param name="fatal">异常对象</param>
  281. public static void Fatal(Exception fatal)
  282. {
  283. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {fatal.Source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}"));
  284. LogInfo log = new LogInfo()
  285. {
  286. LogLevel = LogLevel.Fatal,
  287. Message = fatal.Message,
  288. Time = Now,
  289. ThreadId = Thread.CurrentThread.ManagedThreadId,
  290. Source = fatal.Source,
  291. Exception = fatal,
  292. ExceptionType = fatal.GetType().Name
  293. };
  294. Event?.Invoke(log);
  295. }
  296. /// <summary>
  297. /// 写入fatal级别日志
  298. /// </summary>
  299. /// <param name="source">异常源的类型</param>
  300. /// <param name="fatal">异常对象</param>
  301. public static void Fatal(Type source, Exception fatal)
  302. {
  303. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}"));
  304. LogInfo log = new LogInfo()
  305. {
  306. LogLevel = LogLevel.Fatal,
  307. Message = fatal.Message,
  308. Time = Now,
  309. ThreadId = Thread.CurrentThread.ManagedThreadId,
  310. Source = source.FullName,
  311. Exception = fatal,
  312. ExceptionType = fatal.GetType().Name
  313. };
  314. Event?.Invoke(log);
  315. }
  316. /// <summary>
  317. /// 写入fatal级别日志
  318. /// </summary>
  319. /// <param name="source">异常源的类型</param>
  320. /// <param name="fatal">异常对象</param>
  321. public static void Fatal(Type source, string fatal)
  322. {
  323. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal}"));
  324. LogInfo log = new LogInfo()
  325. {
  326. LogLevel = LogLevel.Fatal,
  327. Message = fatal,
  328. Time = Now,
  329. ThreadId = Thread.CurrentThread.ManagedThreadId,
  330. Source = source.FullName,
  331. //Exception = fatal,
  332. ExceptionType = fatal.GetType().Name
  333. };
  334. Event?.Invoke(log);
  335. }
  336. /// <summary>
  337. /// 写入fatal级别日志
  338. /// </summary>
  339. /// <param name="source">异常源的类型</param>
  340. /// <param name="fatal">异常对象</param>
  341. public static void Fatal(string source, Exception fatal)
  342. {
  343. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}"));
  344. LogInfo log = new LogInfo()
  345. {
  346. LogLevel = LogLevel.Fatal,
  347. Message = fatal.Message,
  348. Time = Now,
  349. ThreadId = Thread.CurrentThread.ManagedThreadId,
  350. Source = source,
  351. Exception = fatal,
  352. ExceptionType = fatal.GetType().Name
  353. };
  354. Event?.Invoke(log);
  355. }
  356. /// <summary>
  357. /// 写入fatal级别日志
  358. /// </summary>
  359. /// <param name="source">异常源的类型</param>
  360. /// <param name="fatal">异常对象</param>
  361. public static void Fatal(string source, string fatal)
  362. {
  363. LogQueue.Enqueue((GetLogPath(), $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal}"));
  364. LogInfo log = new LogInfo()
  365. {
  366. LogLevel = LogLevel.Fatal,
  367. Message = fatal,
  368. Time = Now,
  369. ThreadId = Thread.CurrentThread.ManagedThreadId,
  370. Source = source,
  371. ExceptionType = fatal.GetType().Name
  372. };
  373. Event?.Invoke(log);
  374. }
  375. private static string GetLogPath()
  376. {
  377. string newFilePath;
  378. var logDir = string.IsNullOrEmpty(LogDirectory) ? Path.Combine(Environment.CurrentDirectory, "logs") : LogDirectory;
  379. Directory.CreateDirectory(logDir);
  380. const string extension = ".log";
  381. var fileNameNotExt = Now.ToString("yyyyMMdd");
  382. var fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
  383. var filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList();
  384. if (filePaths.Count > 0)
  385. {
  386. int fileMaxLen = filePaths.Max(d => d.Length);
  387. string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault();
  388. if (new FileInfo(lastFilePath).Length > 1024 * 1024)
  389. {
  390. var no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value;
  391. var parse = int.TryParse(no, out int tempno);
  392. var formatno = $"({(parse ? (tempno + 1) : tempno)})";
  393. var newFileName = string.Concat(fileNameNotExt, formatno, extension);
  394. newFilePath = Path.Combine(logDir, newFileName);
  395. }
  396. else
  397. {
  398. newFilePath = lastFilePath;
  399. }
  400. }
  401. else
  402. {
  403. var newFileName = string.Concat(fileNameNotExt, $"({0})", extension);
  404. newFilePath = Path.Combine(logDir, newFileName);
  405. }
  406. return newFilePath;
  407. }
  408. private static void WriteText(string logPath, string logContent)
  409. {
  410. try
  411. {
  412. if (!File.Exists(logPath))
  413. {
  414. File.CreateText(logPath).Close();
  415. }
  416. using var sw = File.AppendText(logPath);
  417. sw.Write(logContent);
  418. }
  419. catch (Exception)
  420. {
  421. // ignored
  422. }
  423. }
  424. }
  425. }