Logger.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace MV485.helper
  8. {
  9. public class Logger
  10. {
  11. private static readonly object _lock = new object();
  12. private static string _logDirectory = "logs"; // 日志文件存放目录
  13. private static string _logFileName => Path.Combine(_logDirectory, $"{DateTime.Now:yyyy-MM-dd}.log"); // 按日期存放日志文件
  14. public enum LogLevel
  15. {
  16. Debug,
  17. Info,
  18. Warn,
  19. Error
  20. }
  21. static Logger()
  22. {
  23. //暂时不使用
  24. // 确保日志目录存在
  25. /*if (!Directory.Exists(_logDirectory))
  26. {
  27. Directory.CreateDirectory(_logDirectory);
  28. }*/
  29. }
  30. public static void Log(LogLevel level, string message)
  31. {
  32. //暂时不使用
  33. /*string logEntry = FormatLogEntry(level, message);
  34. lock (_lock)
  35. {
  36. // 写入日志文件
  37. File.AppendAllText(_logFileName, logEntry, Encoding.UTF8);
  38. }
  39. // 控制台输出(可选)
  40. Console.Write(logEntry);*/
  41. }
  42. public static void Debug(string message) => Log(LogLevel.Debug, message);
  43. public static void Info(string message) => Log(LogLevel.Info, message);
  44. public static void Warn(string message) => Log(LogLevel.Warn, message);
  45. public static void Error(string message) => Log(LogLevel.Error, message);
  46. private static string FormatLogEntry(LogLevel level, string message)
  47. {
  48. return $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}{Environment.NewLine}";
  49. }
  50. //-------------------------------------------
  51. }
  52. }