![](/img/trans.png)
[英]Dynamically set EventID when logging to Event Viewer using Serilog
[英]Enriching serilog logs with EventId
我想用 eventId 丰富我的日志,以便我可以轻松找到特定类型的事件。 我知道 .netCore 已经有传递给Ilogger 的 EventId 结构。
所以当我在我的代码中这样做时:
_logger.LogInformation(_events.TestEvent,"Test logged.");
我想将 eventId 结构中的 Id 获取到日志的属性。 我尝试编写 ILogEventEnricher 类型的增强器,但无法从 Serilog.Events.LogEvent class 访问 EventId 结构。
还有其他方法吗?
Od 我每次都必须将自定义属性推送到这样的日志吗?
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>();
在你的创业公司
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.