Logger.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace NetCore31BACNetTransfor
  6. {
  7. public static class Logger
  8. {
  9. public static string Dir = "Logs";
  10. static object locker = new object();
  11. public static void Log(string fileName, string msg, bool hasTime = true)
  12. {
  13. try
  14. {
  15. lock (locker)
  16. {
  17. Console.WriteLine(msg);
  18. if (!Directory.Exists(Dir))
  19. Directory.CreateDirectory(Dir);
  20. File.AppendAllLines(Path.Combine(Dir, fileName),
  21. new string[] { (hasTime ? DateTime.Now.ToString("HH:mm:ss ") : "") + msg });
  22. }
  23. }
  24. catch
  25. {
  26. }
  27. }
  28. public static void Log(string msg, bool hasTime = true)
  29. {
  30. Log(DateTime.Today.ToString("yyyyMMdd") + @".txt", msg, hasTime);
  31. }
  32. public static void Warning(string msg)
  33. {
  34. //Log(DateTime.Today.ToString("yyyyMMdd"), msg);
  35. Log(DateTime.Today.ToString("yyyyMMdd") + ".Warnings", msg);
  36. }
  37. public static void Error(string msg)
  38. {
  39. //Log(DateTime.Today.ToString("yyyyMMdd"), msg);
  40. Log(DateTime.Today.ToString("yyyyMMdd") + ".Errors", msg);
  41. }
  42. public static void Error(Exception exp)
  43. {
  44. if (exp == null) return;
  45. Error(exp.Message + "\n" + exp.StackTrace);
  46. }
  47. public static void Error(string preStr, Exception exp)
  48. {
  49. if (exp == null) return;
  50. Error(preStr + ":" + exp.Message + "\n" + exp.StackTrace);
  51. }
  52. }
  53. }