使用 EventId 丰富 serilog 日志

Enriching serilog logs with EventId

我想用 eventId 丰富我的日志,以便我可以轻松找到特定类型的事件。 我知道 .netCore 已经有了 EventId struct that is passed to the Ilogger.

所以当我在我的代码中这样做时:

_logger.LogInformation(_events.TestEvent,"Test logged.");

我想将 eventId 结构中的 Id 获取到日志的属性。 我尝试编写 ILogEventEnricher 类型的增强器,但无法从 Serilog.Events.LogEvent class.

访问 EventId 结构

还有其他方法吗?

我每次都必须将自定义 属性 推送到这样的日志吗?

using(LogContext.PushProperty("EventId", _events.SendingEmailSmarEmailing.Id))
   _logger.LogInformation("Test polling service runned.");

我使用中间件自动推送属性。 这需要 3 个更改;一个 LogEventEnricher 中间件,用于为每个请求推送属性,最后需要注册这些属性。 它通过中间件获取 eventenricher 来工作,它用于在等待 _next() 之前推送属性,它调用你的控制器端点处理程序

 public class CommonEventEnricher : ILogEventEnricher
    {
        private readonly YourOperationContext _operationContext;

        public CommonEventEnricher(YourOperationContext context)
        {
            _operationContext = context;
        }

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("EventId", _operationContext.EventId));
        }
    }
    public class LoggingInterceptorMiddleware
    {
        private readonly RequestDelegate _next;

        public LoggingInterceptorMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, ILogEventEnricher logEventEnricher)
        {
            using (LogContext.Push(logEventEnricher))
            {
                await _next(context);
            }
        }
    }

最后:

applicationBuilder.UseMiddleware<LoggingInterceptorMiddleware>()
serviceCollection.AddScoped<ILogEventEnricher, CommonEventEnricher>();

在你的创业公司