FileLogger.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.IO;
  3. namespace AutoFocusTool.Logging
  4. {
  5. /// <summary>
  6. /// 静态文件日志器:程序启动时按时间戳建一个文件,本次运行所有日志写入它。
  7. /// 线程安全(lock),每条 flush。格式:HH:mm:ss.fff [级别] [类别] 消息
  8. /// </summary>
  9. public static class FileLogger
  10. {
  11. private static readonly object _lock = new object();
  12. private static string _path;
  13. /// <summary>启动时调用一次:在 Logs/ 下建 yyyy-MM-dd_HHmmss.log。</summary>
  14. public static void Init()
  15. {
  16. lock (_lock)
  17. {
  18. if (_path != null) return;
  19. string dir = @"C:\claudeFile\TL\AutoFocusTool\Logs";
  20. Directory.CreateDirectory(dir);
  21. _path = Path.Combine(dir, $"{DateTime.Now:yyyy-MM-dd_HHmmss}.log");
  22. Write("INFO", "APP", "==== 日志开始 ====");
  23. }
  24. }
  25. public static void Info(string category, string msg) => Write("INFO", category, msg);
  26. public static void Action(string category, string msg) => Write("ACTION", category, msg);
  27. public static void Data(string category, string msg) => Write("DATA", category, msg);
  28. public static void Warn(string category, string msg) => Write("WARN", category, msg);
  29. public static void Error(string category, string msg) => Write("ERROR", category, msg);
  30. private static void Write(string level, string category, string msg)
  31. {
  32. try
  33. {
  34. lock (_lock)
  35. {
  36. if (_path == null) return; // 未 Init 则静默丢弃
  37. string line = $"{DateTime.Now:HH:mm:ss.fff} [{level,-6}] [{category,-6}] {msg}";
  38. File.AppendAllText(_path, line + Environment.NewLine);
  39. }
  40. }
  41. catch { /* 日志失败不能影响主流程 */ }
  42. }
  43. }
  44. }