LogManager.cs 18 KB

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