LogHub.cs 2.3 KB

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