RealLogger.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using MeterVision.Config;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MeterVision.Helper
  9. {
  10. public sealed class RealLogger
  11. {
  12. private static readonly object _lock = new object();
  13. private static RealLogger _instance;
  14. private readonly string _logFilePath;
  15. /// <summary>
  16. /// 获取单例实例
  17. /// </summary>
  18. public static RealLogger GetInstance()
  19. {
  20. if (_instance == null)
  21. {
  22. lock (_lock)
  23. {
  24. if (_instance == null)
  25. {
  26. _instance = new RealLogger();
  27. }
  28. }
  29. }
  30. return _instance;
  31. }
  32. private RealLogger()
  33. {
  34. // 日志文件路径
  35. //_logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app.log");
  36. _logFilePath = CfginiItem.GetConfigItem().RealLogPath;
  37. if (!Directory.Exists(_logFilePath))
  38. {
  39. Directory.CreateDirectory(_logFilePath);
  40. }
  41. _logFilePath = Path.Combine(_logFilePath, ThisApp.GetNowTime_yyyyMMddHHmmss() + ".txt");
  42. // 确保日志文件存在
  43. if (!File.Exists(_logFilePath))
  44. {
  45. File.Create(_logFilePath).Close();
  46. }
  47. }
  48. /// <summary>
  49. /// 追加日志内容,并写入文件
  50. /// </summary>
  51. public void Log(string message)
  52. {
  53. //string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}";
  54. string logEntry = message;
  55. // 控制台输出
  56. Console.WriteLine(logEntry);
  57. // 写入文件(追加模式)
  58. lock (_lock)
  59. {
  60. using (StreamWriter writer = new StreamWriter(_logFilePath, true, Encoding.UTF8))
  61. {
  62. writer.WriteLine(logEntry);
  63. writer.Flush();
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// 追加日志(异步版本)
  69. /// </summary>
  70. //public async void LogAsync(string message)
  71. //{
  72. // string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}";
  73. // // 控制台输出
  74. // Console.WriteLine(logEntry);
  75. // // 异步写入文件(追加模式)
  76. // lock (_lock)
  77. // {
  78. // using (StreamWriter writer = new StreamWriter(_logFilePath, true, Encoding.UTF8))
  79. // {
  80. // writer.WriteLine(logEntry);
  81. // writer.Flush();
  82. // }
  83. // }
  84. //}
  85. /// <summary>
  86. /// 读取日志内容
  87. /// </summary>
  88. public string ReadLogs()
  89. {
  90. lock (_lock)
  91. {
  92. return File.ReadAllText(_logFilePath);
  93. }
  94. }
  95. public void Close()
  96. {
  97. lock (_lock)
  98. {
  99. _instance = null;
  100. }
  101. }
  102. //--------------------------------------------------
  103. }
  104. //------------------------------------------------------
  105. }