LogManager.cs 18 KB

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