LogHub.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using Newtonsoft.Json;
  2. using ServiceCenter.Extensions;
  3. using ServiceCenter.Redis;
  4. using System.Collections.Concurrent;
  5. using System.IO;
  6. using WCS.Core;
  7. namespace ServiceCenter
  8. {
  9. public class LogHub
  10. {
  11. /// <summary>
  12. /// 日志队列
  13. /// </summary>
  14. public static ConcurrentQueue<LogModel> Logs = new ConcurrentQueue<LogModel>();
  15. /// <summary>
  16. /// 发布一条日志记录
  17. /// </summary>
  18. /// <param name="path">路径</param>
  19. /// <param name="title">文件名</param>
  20. /// <param name="con">内容</param>
  21. public static void Publish(string path, string title, string con)
  22. {
  23. RedisHub.Default.RPush("LogHub", JsonConvert.SerializeObject(new LogModel
  24. {
  25. path = path,
  26. Title = title,
  27. Con = con
  28. }));
  29. }
  30. /// <summary>
  31. /// 增加一条处理日志
  32. /// </summary>
  33. /// <param name="title">文件名</param>
  34. /// <param name="con">内容</param>
  35. public static void InterfaceProcessLog(string title, string con)
  36. {
  37. RedisHub.Default.RPush("LogHub", JsonConvert.SerializeObject(new LogModel
  38. {
  39. path = $"D:\\WCSLogs\\{DateTime.Now.yyyyMMdd()}\\接口处理日志",
  40. Title = $"{title}.txt",
  41. Con = $"{DateTime.Now.yyyyMMddhhmmssf()}--[{Thread.CurrentThread.ManagedThreadId}]--{con}\n"
  42. }));
  43. }
  44. public static void init()
  45. {
  46. while (true)
  47. {
  48. var logHub = RedisHub.Default.LPop("LogHub");
  49. LogModel log = new LogModel();
  50. try
  51. {
  52. if (logHub != null)
  53. {
  54. log = JsonConvert.DeserializeObject<LogModel>(logHub);
  55. if (log != null)
  56. {
  57. if (!Directory.Exists(log.path)) Directory.CreateDirectory(log.path);
  58. File.AppendAllText(Path.Combine(log.path, log.Title), log.Con);
  59. }
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. var path = $"D:\\WCSLogs\\{DateTime.Now.yyyyMMdd()}\\日志处理进程";
  65. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  66. File.AppendAllText(Path.Combine($"D:\\WCSLogs\\{DateTime.Now.yyyyMMdd()}\\日志处理进程", "Error.txt"), $"{JsonConvert.SerializeObject(log)}--{ex.Message}--{ex.StackTrace}\n");
  67. }
  68. }
  69. }
  70. }
  71. public class LogModel
  72. {
  73. public string path { get; set; }
  74. public string Title { get; set; }
  75. public string Con { get; set; }
  76. }
  77. }