VJsonFileLogger.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using VCommon.Diagnostics;
  5. using VCommon.Json;
  6. namespace VCommon.Logging
  7. {
  8. public class VJsonFileLogger : FileLogger
  9. {
  10. private readonly bool _includeSourceStackFrameOnly;
  11. private readonly IVJsonSerializer _jsonSerializer;
  12. public VJsonFileLogger(IVJsonSerializer jsonSerializer = null,
  13. int mbSplit = 10, int? preserveDays = null, string logTo = null, bool enableAll = false,
  14. bool includeSourceStackFrameOnly = true) : base(mbSplit, preserveDays, logTo, enableAll)
  15. {
  16. _includeSourceStackFrameOnly = includeSourceStackFrameOnly;
  17. _jsonSerializer = jsonSerializer ?? VJsonLogSerializer.Instance;
  18. }
  19. protected override string FormatMessage(DateTime time, Level level, string summary, object moreInfo)
  20. {
  21. var logAt = new StackTrace(true).GetFormattedDetailStackTraceText(typeof(Logger),_includeSourceStackFrameOnly);
  22. var obj = new { moreInfo, logAt };
  23. string json;
  24. try
  25. {
  26. json = _jsonSerializer.SerializeObject(obj);
  27. }
  28. catch (Exception exception)
  29. {
  30. json = _jsonSerializer.SerializeObject(new { LoggerWarn = "json serialize fail", ToString = obj.ToString(), LoggerException = exception, logAt });
  31. }
  32. var currentThread = Thread.CurrentThread;
  33. return $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {level} {currentThread.Name ?? "Unamed"}({currentThread.ManagedThreadId})"
  34. + $"{Environment.NewLine}{summary?.Replace("\r", "").Replace("\n", "")}"
  35. + $"{Environment.NewLine}{json}"
  36. + Environment.NewLine;
  37. }
  38. }
  39. }