SerilogHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Serilog;
  2. using Serilog.Core;
  3. using Serilog.Events;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace XdCxRhDW.Framework
  12. {
  13. public static class SerilogHelper
  14. {
  15. public static void BuildLogger(bool usePID = true)
  16. {
  17. string outputTemplate;
  18. if (usePID)
  19. outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}[线程={ThreadId}][PID={PID}][{Level:u3}]{Message:lj}{NewLine}\t{Exception}";
  20. else
  21. outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}[线程={ThreadId}][{Level:u3}]{Message:lj}{NewLine}\t{Exception}";
  22. Serilog.Log.Logger = new Serilog.LoggerConfiguration()
  23. .Enrich.FromLogContext()
  24. .Enrich.With(new SerilogEnricher(usePID))
  25. .WriteTo.Console(outputTemplate: outputTemplate)
  26. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Information)
  27. .WriteTo.File("Logs\\Info\\.log", rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  28. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Warning)
  29. .WriteTo.File("Logs\\Warning\\.log", rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  30. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
  31. .WriteTo.File("Logs\\Error\\.log", rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  32. .CreateLogger();
  33. }
  34. }
  35. /// <summary>
  36. /// Serilog日志添加线程ID
  37. /// </summary>
  38. public class SerilogEnricher : ILogEventEnricher
  39. {
  40. private bool useProcessId;
  41. private string PID;
  42. public SerilogEnricher(bool useProcessId = false)
  43. {
  44. this.useProcessId = useProcessId;
  45. if (useProcessId)
  46. {
  47. this.PID = Process.GetCurrentProcess().Id.ToString("D5");
  48. }
  49. }
  50. /// <summary>
  51. /// 在日志中添加线程ID
  52. /// </summary>
  53. /// <param name="logEvent"></param>
  54. /// <param name="propertyFactory"></param>
  55. public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
  56. {
  57. logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
  58. "ThreadId", Thread.CurrentThread.ManagedThreadId.ToString("D3")));
  59. if (useProcessId)
  60. {
  61. logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("PID", PID));
  62. }
  63. }
  64. }
  65. }