With Serilog.AspNetCore, how do IDiagnosticContext.Set and RequestLoggingOptions.EnrichDiagnosticContext add user and tenant ids to the single request completion event?
answer
- IDiagnosticContext is a singleton
- AsyncLocal collector per request
- Set only reaches the completion event
- EnrichDiagnosticContext runs at completion
- SetException for handled exceptions
basics
~10 sInject IDiagnosticContext and call Set("BookingId", id) during the request, or set common values centrally in RequestLoggingOptions.EnrichDiagnosticContext; both become properties of that request's one completion event only, not of other log events.
solid answer
~50 s`IDiagnosticContext` is registered as a **singleton** by `AddSerilog`, so it can be injected anywhere. The request logging middleware begins an ambient, `AsyncLocal`-based collection for each request; `Set(name, value, destructureObjects)` adds or replaces a property in that collection, and the middleware attaches the collected properties to the request's completion event. Outside a request (no collection in progress) `Set` does nothing. For values every request needs - user id, tenant id, client IP - use `options.EnrichDiagnosticContext = (ctx, http) => ...`, which runs once at completion, after the endpoint, so authentication has already populated `HttpContext.User`. It only runs if the completion level is enabled. `SetException(ex)` attaches an exception that was handled further in, so the completion event still carries it. These properties are not added to other events in the request - that is what `LogContext` is for.
go deeper
Know that injecting IDiagnosticContext and calling Set adds a property to the request summary line.
Explain the singleton plus AsyncLocal collector, that Set affects only the completion event, and when EnrichDiagnosticContext runs.
Use SetException for handled exceptions, know the precedence of default properties, and combine the diagnostic context with LogContext for correlation.
Define a per-request property contract, such as user, tenant and booking ids, that every service sets on its completion event.
## One event, many facts Request logging writes a single completion event per request. The idea of the **diagnostic context** is to make that event carry everything you want to know about the request - which booking, which user, which tenant, how many rooms were searched - instead of writing a separate event for each fact. ## The pieces - **`IDiagnosticContext`** (namespace `Serilog`, from `Serilog.Extensions.Hosting`) has two members: `Set(string propertyName, object? value, bool destructureObjects = false)` and `SetException(Exception exception)`. - `AddSerilog` registers `DiagnosticContext` and `IDiagnosticContext` as **singletons**. That is safe because the state is not in the object: it lives in an ambient collector stored in an `AsyncLocal`. - `RequestLoggingMiddleware` calls `BeginCollection()` at the start of each request and disposes the collector at the end, so values set anywhere in that request's async flow are collected. If `Set` is called when no collection is active - in a background service, or before the middleware - nothing happens and nothing throws. ## Setting values in a hotel-booking API Inside an endpoint or service: ```csharp app.MapPost("/api/bookings", async (CreateBooking cmd, BookingService svc, IDiagnosticContext diag) => { var booking = await svc.CreateAsync(cmd); diag.Set("BookingId", booking.Id); diag.Set("Nights", cmd.Nights); return TypedResults.Created($"/api/bookings/{booking.Id}", booking); }); ``` Centrally, for every request: ```csharp app.UseSerilogRequestLogging(options => { options.EnrichDiagnosticContext = (diag, http) => { diag.Set("UserId", http.User.FindFirst("sub")?.Value); diag.Set("TenantId", http.User.FindFirst("tenant")?.Value); }; }); ``` The completion event then reads: `HTTP POST /api/bookings responded 201 in 48.2210 ms`, with `BookingId`, `Nights`, `UserId` and `TenantId` as properties. ## Timing and precedence rules From the middleware source: 1. `EnrichDiagnosticContext` runs **at completion**, after the rest of the pipeline - so the user is authenticated and the response status is known. 2. It runs only if the chosen level is enabled; a filtered-out request costs nothing. 3. Collected properties come first and the default properties (`RequestMethod`, `RequestPath`, `StatusCode`, `Elapsed`) are added after them. When names collide, the **later one wins**, so `Set("RequestPath", ...)` cannot change the logged path. 4. Repeated `Set` calls with the same name replace the earlier value. 5. With `destructureObjects: true`, an object is destructured using the logger's destructuring rules, exactly as with `@` in a template. ## Handled exceptions When an exception handler deeper in the pipeline turns an exception into a 500 response, the request logger sees a status of 500 (and logs at `Error`) but no exception. Calling `diagnosticContext.SetException(ex)` from the handler attaches it to the completion event. This matters more in ASP.NET Core 10, where the exception handler middleware by default no longer writes its own diagnostics for exceptions an `IExceptionHandler` handled, so the completion event may be the only place the stack trace appears. ## What to keep out - **Personal data.** The completion event is the most widely queried event in most systems; prefer ids (`UserId`) to names or emails. - **Large objects.** `destructureObjects: true` on a booking aggregate copies the whole graph into every request line; set the few fields you search on. - **Values you need on other events.** The diagnostic context reaches only the completion event, so correlation ids that every event must carry belong on `LogContext` instead. ## Diagnostic context versus LogContext | | `IDiagnosticContext.Set` | `LogContext.PushProperty` | |---|---|---| | Appears on | the request completion event only | every event in scope (with `Enrich.FromLogContext()`) | | Scope ends | when the request completes | when the returned `IDisposable` is disposed | | Typical use | summary facts about the request | correlating all events of an operation | They complement each other: push a correlation id onto `LogContext` so every event carries it, and `Set` the outcome facts once on the summary event.
- Why can IDiagnosticContext be a singleton when the values it collects are per request?The singleton holds no request data. `Set` writes into an ambient collector stored in an `AsyncLocal`, which the request logging middleware creates at the start of each request and disposes at the end. Each request's async flow sees its own collector, so concurrent requests never mix their properties.
- A background job calls diagnosticContext.Set("JobId", id) and the value never shows up anywhere. Why?No request logging middleware began a collection on that flow, so there is no ambient collector and `Set` silently does nothing. For background work, use `LogContext.PushProperty` with `Enrich.FromLogContext()`, or log the value in the job's own events.
- IDiagnosticContext.Set adds the property to every log event in the request
- IDiagnosticContext must be registered as scoped to be request-safe
- EnrichDiagnosticContext runs at the start of the request, before authentication
- Set("RequestPath", ...) overrides the path shown on the completion event
- Set outside a request throws InvalidOperationException
Assumes Serilog.AspNetCore 10.0 with Serilog.Extensions.Hosting 10.0 on ASP.NET Core 10, where ExceptionHandlerOptions.SuppressDiagnosticsCallback by default suppresses diagnostics for exceptions an IExceptionHandler handled.