![](/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.