简体   繁体   English

使用 EventId 丰富 serilog 日志

[英]Enriching serilog logs with EventId

I would like to enrich my logs with eventId so that I can easily find certain type of events.我想用 eventId 丰富我的日志,以便我可以轻松找到特定类型的事件。 I know that the .netCore already has the EventId struct that is passed to the Ilogger .我知道 .netCore 已经有传递给Ilogger 的 EventId 结构

So when I do this in my code:所以当我在我的代码中这样做时:

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

I would like to get the Id inside the eventId struct to the properties of the log.我想将 eventId 结构中的 Id 获取到日志的属性。 I tryed writing my on enricher of type ILogEventEnricher but there is no way to access the EventId struct from Serilog.Events.LogEvent class.我尝试编写 ILogEventEnricher 类型的增强器,但无法从 Serilog.Events.LogEvent class 访问 EventId 结构。

Is there an other way to do this?还有其他方法吗?

Od do I have to push an custom property to logs like this every time? Od 我每次都必须将自定义属性推送到这样的日志吗?

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

I use middleware to automatically push properties.我使用中间件自动推送属性。 That requires 3 changes;这需要 3 个更改; an LogEventEnricher, Middleware to push properties for each request, and finally those needs to be registered.一个 LogEventEnricher 中间件,用于为每个请求推送属性,最后需要注册这些属性。 It works by the middleware getting the eventenricher injected, which it uses to pushproperties before awaiting _next(), which call your controllers endpoint handler它通过中间件获取 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);
            }
        }
    }

And then finally:最后:

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

in your startup在你的创业公司

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM