I would like to enrich my logs with eventId so that I can easily find certain type of events. I know that the .netCore already has the EventId struct that is passed to the Ilogger.
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. I tryed writing my on enricher of type ILogEventEnricher but there is no way to access the EventId struct from Serilog.Events.LogEvent class.
Is there an other way to do this?
Od do I have to push an custom property to logs like this every time?
using(LogContext.PushProperty("EventId", _events.SendingEmailSmarEmailing.Id))
_logger.LogInformation("Test polling service runned.");
I use middleware to automatically push properties. That requires 3 changes; an LogEventEnricher, Middleware to push properties for each request, and finally those needs to be registered. It works by the middleware getting the eventenricher injected, which it uses to pushproperties before awaiting _next(), which call your controllers endpoint handler
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