Logger.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. namespace DRG.DRGInterfaceClient
  5. {
  6. /// <summary>本地滚动日志:写 DRGInterfaceClient.log,并提供界面订阅、打开、清空。</summary>
  7. internal static class Logger
  8. {
  9. private static readonly string LogPath =
  10. Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DRGInterfaceClient.log");
  11. private static readonly object _lock = new object();
  12. public static event Action<string> OnLog;
  13. public static void Info(string msg) { Write("INFO", msg); }
  14. public static void Warn(string msg) { Write("WARN", msg); }
  15. public static void Error(string msg, Exception ex = null)
  16. {
  17. string m = msg;
  18. if (ex != null) m += " | " + ex.GetType().Name + ": " + ex.Message;
  19. Write("ERROR", m);
  20. }
  21. private static void Write(string level, string msg)
  22. {
  23. string line = string.Format("[{0}] [{1}] {2}",
  24. DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), level, msg);
  25. lock (_lock)
  26. {
  27. try
  28. {
  29. RollIfNeeded();
  30. File.AppendAllText(LogPath, line + Environment.NewLine);
  31. }
  32. catch { }
  33. }
  34. try { OnLog?.Invoke(line); } catch { }
  35. }
  36. private static void RollIfNeeded()
  37. {
  38. try
  39. {
  40. if (File.Exists(LogPath))
  41. {
  42. long size = new FileInfo(LogPath).Length;
  43. long max = (long)Config.Current.MaxLogSizeMB * 1024 * 1024;
  44. if (size > max)
  45. {
  46. string bak = LogPath + ".1";
  47. if (File.Exists(bak)) File.Delete(bak);
  48. File.Move(LogPath, bak);
  49. }
  50. }
  51. }
  52. catch { }
  53. }
  54. public static string ReadAll()
  55. {
  56. try { return File.Exists(LogPath) ? File.ReadAllText(LogPath) : ""; }
  57. catch { return ""; }
  58. }
  59. public static void OpenLogFile()
  60. {
  61. try { Process.Start(LogPath); }
  62. catch (Exception ex) { Error("打开日志文件失败", ex); }
  63. }
  64. public static void Clear()
  65. {
  66. lock (_lock)
  67. {
  68. try { if (File.Exists(LogPath)) File.WriteAllText(LogPath, ""); }
  69. catch { }
  70. }
  71. }
  72. }
  73. }