I tried the following answer:
Namely this:
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
// string body = your logic to get body from httpContext.Request.Body
diagnosticContext.Set("Body", body);
};
But in my case body is an empty string. My code for reading body from httpContext is based on this solution:
And it works in my custom middleware that I created for global exception handling. It does not use Serilog though. Just some quick poor man's approach to structured logging via Newtonsoft serialization.
I found this enricher on nuget:
But it seems outdated, and the Serilog syntax has changed since then.
I also checked this related official Serilog ticket which was closed.
Is this workflow of adding custom properties from http request not supported natively by Serilog? Quote from their github repo:
Thanks for raising this. I think copying and modifying https://github.com/serilog/serilog-aspnetcore/blob/dev/src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs will be the simplest way forwards (I agree this is a bit unfortunate
For example, if a request has a field called patientId, log that. Because there are infinite number of ways to log properties from http context, it's fine to ask developer to provide that custom method. But creating a custom middleware for this sounds like an overkill. Also multiple middlewares might not work well together.
Is there a way to log custom properties from http request? I have my own global exception middleware, but not sure how to make it work together with Serilog. Or any other option. Main requirement - custom properties should ONLY be logged in case of an error.
One workaround I found is manually logging the error from my global exception middleware. In Program.cs, remove the following line:
app.UseSerilogRequestLogging();
Then in middleware, add
using Serilog;
// ... some code here, then in catch block
Log.Error("Unhandled exception occured when processing request {@errorRequest}.",
errorRequest);
// ... more code, set 500 status and custom props on response
Where errorRequest
would contain the necessary properties.