By default logging in ASP.NET Core generates a lot of log messages for every request. Thanks to the Serilog's RequestLoggingMiddleware
that comes with the Serilog.AspNetCore NuGet package you can reduce this to a single log message:
But what if you want to extend the log message with some extra data?
This can be done by setting values on the IDiagnosticContext
instance. This interface is injected as a singleton in the DI container.
Here is an example where we add some header info to the request log:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
// ... Other middleware | |
app.UseSerilogRequestLogging(opts | |
=> opts.EnrichDiagnosticContext = (diagnosticsContext, httpContext)=>{ | |
var request = httpContext.Request; | |
diagnosticsContext.Set("Custom Header value", request.Headers["custom-header-value"]); | |
}); | |
// ... Other middleware | |
} |