Logger.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace AIDiagnosisDemo.Infrastucture
  5. {
  6. public class Logger
  7. {
  8. private static readonly object Locker = new object();
  9. private static string LogDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  10. static Logger()
  11. {
  12. }
  13. private static string FilePath
  14. {
  15. get { return Path.Combine(LogDir, DateTime.Now.ToString("yyyyMMdd") + ".txt"); }
  16. }
  17. private static void Write(string msg)
  18. {
  19. lock (Locker)
  20. {
  21. if (!File.Exists(FilePath))
  22. {
  23. if (!Directory.Exists(LogDir))
  24. Directory.CreateDirectory(LogDir);
  25. }
  26. using (var writer = new StreamWriter(FilePath, true, Encoding.UTF8))
  27. {
  28. writer.WriteLine(msg);
  29. }
  30. }
  31. }
  32. public static void Debug(string msg)
  33. {
  34. var now = DateTime.Now;
  35. msg = string.Format("[{0} {1}] : {2}", "Debug", $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}", msg);
  36. Write(msg);
  37. }
  38. public static void Info(string msg)
  39. {
  40. var now = DateTime.Now;
  41. msg = string.Format("[{0} {1}] : {2}", "Info", $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}", msg);
  42. Write(msg);
  43. }
  44. public static void Error(string msg)
  45. {
  46. var now = DateTime.Now;
  47. msg = string.Format("[{0} {1}] : {2}", "Error", $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}", msg);
  48. Write(msg);
  49. }
  50. public static void Error(string desc, Exception exception)
  51. {
  52. var now = DateTime.Now;
  53. var msg = string.Format("[{0} {1}] : {2} {3}", "Error", $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}", desc, exception);
  54. Write(msg);
  55. }
  56. }
  57. }