RequestLogger.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using LJLib.Tools.File;
  2. using System;
  3. using System.IO;
  4. using System.Threading;
  5. namespace LJLib.TextLog
  6. {
  7. internal class RequestLogger : ILogger
  8. {
  9. private readonly string _logDir;
  10. private Timer _timer;
  11. private readonly object _syncRoot = new object();
  12. public RequestLogger(string logDir = null)
  13. {
  14. // 默认目录为执行目录下的 log 文件夹
  15. _logDir = logDir ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
  16. if (!Directory.Exists(_logDir)) Directory.CreateDirectory(_logDir);
  17. // 创建定时器:立即启动,每隔24小时执行一次
  18. _timer = new Timer(CleanupOldLogs, null, 0, 24 * 60 * 60 * 1000);
  19. }
  20. /// <summary>
  21. /// 获取今天的日志文件全路径
  22. /// </summary>
  23. private string GetTodayLogFile()
  24. {
  25. string fileName = $"REQUEST_{DateTime.Now:yyyyMMdd}.log";
  26. return Path.Combine(_logDir, fileName);
  27. }
  28. /// <summary>
  29. /// 写入日志
  30. /// </summary>
  31. public void WriteLog(string msg)
  32. {
  33. try
  34. {
  35. lock (_syncRoot)
  36. {
  37. string filePath = GetTodayLogFile();
  38. using (StreamWriter sw = new StreamWriter(filePath, true))
  39. {
  40. sw.WriteLine("====================================================================");
  41. sw.WriteLine($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
  42. sw.WriteLine("--------------------------------------------------------------------");
  43. sw.WriteLine(msg);
  44. sw.WriteLine("====================================================================");
  45. sw.WriteLine();
  46. }
  47. }
  48. }
  49. catch
  50. {
  51. // 这里可考虑写到系统事件日志或忽略
  52. }
  53. }
  54. /// <summary>
  55. /// 清理7天前的日志文件
  56. /// </summary>
  57. private void CleanupOldLogs(object state)
  58. {
  59. try
  60. {
  61. var files = Directory.GetFiles(_logDir, "REQUEST_*.log");
  62. DateTime threshold = DateTime.Now.AddDays(-7);
  63. foreach (var file in files)
  64. {
  65. string fileName = Path.GetFileNameWithoutExtension(file);
  66. // 格式: REQUEST_yyyyMMdd
  67. if (fileName.Length == "REQUEST_yyyyMMdd".Length &&
  68. DateTime.TryParseExact(fileName.Replace("REQUEST_", ""),
  69. "yyyyMMdd",
  70. null,
  71. System.Globalization.DateTimeStyles.None,
  72. out DateTime logDate))
  73. {
  74. if (logDate < threshold.Date)
  75. {
  76. File.Delete(file);
  77. }
  78. }
  79. }
  80. }
  81. catch
  82. {
  83. }
  84. }
  85. }
  86. }