Logger.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Threading;
  5. namespace AICustomizeSDKDemo.Infrastucture
  6. {
  7. public class Logger
  8. {
  9. private static string _filePath;
  10. private static readonly object Locker = new object();
  11. private static string _logDir;
  12. public static string LogDir
  13. {
  14. get => _logDir;
  15. set
  16. {
  17. if (_logDir != value)
  18. {
  19. _logDir = value;
  20. if (!Directory.Exists(LogDir))
  21. {
  22. Directory.CreateDirectory(LogDir);
  23. }
  24. var now = DateTime.Now;
  25. var logTag = $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}";
  26. _filePath = Path.Combine(LogDir, $"Log_{logTag}.log");
  27. }
  28. }
  29. }
  30. static Logger()
  31. {
  32. LogDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  33. }
  34. private static void Write(string msg)
  35. {
  36. lock (Locker)
  37. {
  38. using (var writer = new StreamWriter(_filePath, true, Encoding.UTF8))
  39. {
  40. writer.WriteLine(msg);
  41. }
  42. }
  43. }
  44. public static void Debug(string msg)
  45. {
  46. var now = DateTime.Now;
  47. msg = $"[{now:yyyyMMddHHmmss},{now.Millisecond:d3}]-D: [Thread:{Thread.CurrentThread.ManagedThreadId}]{msg}";
  48. Write(msg);
  49. }
  50. public static void Info(string msg)
  51. {
  52. var now = DateTime.Now;
  53. msg = $"[{now:yyyyMMddHHmmss},{now.Millisecond:d3}]-I: [Thread:{Thread.CurrentThread.ManagedThreadId}]{msg}";
  54. Write(msg);
  55. }
  56. public static void Error(string msg)
  57. {
  58. var now = DateTime.Now;
  59. msg = $"[{now:yyyyMMddHHmmss},{now.Millisecond:d3}]-E: [Thread:{Thread.CurrentThread.ManagedThreadId}]{msg}";
  60. Write(msg);
  61. }
  62. public static void Warning(string msg)
  63. {
  64. var now = DateTime.Now;
  65. msg = $"[{now:yyyyMMddHHmmss},{now.Millisecond:d3}]-W: [Thread:{Thread.CurrentThread.ManagedThreadId}]{msg}";
  66. Write(msg);
  67. }
  68. }
  69. }