Improving request logs with custom DiagnosticContext properties
In this recipe, we’ll enhance Serilog’s request logging middleware to include additional useful information in a single, consolidated log entry for each request. We’ll use IDiagnosticContext
and EnrichDiagnosticContext
to add custom properties that aren’t logged by default.
Getting ready
The starter project can be found here: https://github.com/PacktPublishing/ASP.NET-9-Web-API-Cookbook/tree/main/start/chapter05/EnrichDiagnosticContext. Clone the project or continue from the preceding recipe.
Make sure Docker Desktop or your Docker daemon is running with the Seq container. The docker compose
file is included in the starter project:
docker info docker compose up -d
The starter project already has the required Serilog NuGet packages installed.
How to do it…
- Create a new
Middleware
folder. In this folder, let’s create a new file calledDiagnosticContextEnricher...