LogUtil.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Text;
  3. namespace IMCS.CCS.Common
  4. {
  5. using NLog;
  6. /// <summary>
  7. ///日志
  8. /// </summary>
  9. public static class LogUtil
  10. {
  11. private static Logger Logger { get; set; }
  12. public static void Init(Logger logger)
  13. {
  14. Logger = logger;
  15. }
  16. /// <summary>
  17. /// 日志对象
  18. /// </summary>
  19. /// <returns></returns>
  20. public static Logger GetLogger() => Logger;
  21. /// <summary>
  22. /// 写入日志
  23. /// </summary>
  24. /// <param name="text"></param>
  25. public static void Write(string text)
  26. {
  27. Logger.Info(text);
  28. }
  29. /// <summary>
  30. /// Debug
  31. /// </summary>
  32. /// <param name="text"></param>
  33. public static void WriteDebug(string text)
  34. {
  35. Logger.Debug(text);
  36. }
  37. /// <summary>
  38. /// 写入日志
  39. /// </summary>
  40. /// <param name="text"></param>
  41. /// <param name="exception"></param>
  42. public static void Write(string text, Exception exception)
  43. {
  44. WriteError(exception, null, sb => { sb.Append($"{text}\r\n"); });
  45. }
  46. /// <summary>
  47. /// 写入日志
  48. /// </summary>
  49. /// <param name="exception"></param>
  50. /// <param name="userHostAddress"></param>
  51. /// <param name="callBack"></param>
  52. public static void WriteError(Exception exception, string userHostAddress,
  53. Action<StringBuilder> callBack = null)
  54. {
  55. var sb = new StringBuilder();
  56. var message = "异常信息: " + exception.Message;
  57. var source = "错误源:" + exception.Source;
  58. var stackTrace = "堆栈信息:" + exception.StackTrace;
  59. sb.Append($"\r\n");
  60. callBack?.Invoke(sb);
  61. if (!string.IsNullOrWhiteSpace(userHostAddress))
  62. {
  63. sb.Append($"{userHostAddress}\r\n");
  64. }
  65. if (!string.IsNullOrWhiteSpace(message))
  66. {
  67. sb.Append($"{message}\r\n");
  68. }
  69. if (!string.IsNullOrWhiteSpace(source))
  70. {
  71. sb.Append($"{source}\r\n");
  72. }
  73. if (!string.IsNullOrWhiteSpace(stackTrace))
  74. {
  75. sb.Append($"{stackTrace}\r\n");
  76. }
  77. Logger.Error(exception, sb.ToString());
  78. }
  79. }
  80. }