skip to content

What does Serilog.AspNetCore's UseSerilogRequestLogging() log for each request, at which level, and why does its position in the middleware pipeline matter?

level: middleimportance: must knowfreq 60%

answer

  1. one completion event per request
  2. HTTP {RequestMethod} {RequestPath} responded ...
  3. Error on exception or status > 499
  4. times only what runs after it
  5. quiet Microsoft.AspNetCore.* to Warning

basics

~20 s

It writes one event per request: "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms", at Error when an exception escapes or the status exceeds 499, else Information. It only times and logs middleware registered after it.

solid answer

~40 s

`app.UseSerilogRequestLogging()` adds a middleware that starts a timer, calls the rest of the pipeline, and then writes **one** completion event with `RequestMethod`, `RequestPath`, `StatusCode` and `Elapsed`, using the template `HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms`. The default level is `Error` if an exception propagated or the status code is above 499, otherwise `Information` - so 4xx responses are Information. It is meant to stand in for the several events ASP.NET Core writes per request, which you silence yourself by raising `Microsoft.AspNetCore.Hosting`, `Mvc` and `Routing` to `Warning`. It sees only what runs after it: place it early, before the endpoints, and anything registered before it that ends the request - such as `UseStaticFiles()` serving a file - is neither timed nor logged.

go deeper

for a junior

Know that app.UseSerilogRequestLogging() writes one summary line per request with method, path, status and elapsed time.

for a middle

Explain the default template and level rule, the need to raise Microsoft.AspNetCore overrides, and why placement decides what is timed.

for a senior

Handle exceptions and handlers around it, tune GetLevel for probes and slow requests, and know it defaults to the static Log.Logger.

for a principal

Decide which per-request fields every service must emit on its completion event, so dashboards and SLO queries work uniformly.

## The problem it solves With default logging, ASP.NET Core writes several events per request from `Microsoft.AspNetCore.Hosting`, `Microsoft.AspNetCore.Routing` and, for controllers, `Microsoft.AspNetCore.Mvc` - request starting, executing and executed endpoint or action, request finished. They are useful when debugging and expensive at scale. Serilog's request logging middleware condenses a request into **one** structured event. ## The completion event The middleware, `RequestLoggingMiddleware`, runs this sequence: 1. Record a start timestamp and begin a diagnostic-context collection for the request. 2. `await` the rest of the pipeline. 3. Compute the elapsed milliseconds and read the response status code. 4. Choose the level with `RequestLoggingOptions.GetLevel` and stop if the logger is not enabled for it. 5. Write a `LogEvent` with the configured template, the collected diagnostic properties, and the default properties `RequestMethod`, `RequestPath`, `StatusCode` and `Elapsed`, stamped with the current activity's trace and span ids. The defaults, from `RequestLoggingOptions`: | Option | Default | |---|---| | `MessageTemplate` | `HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms` | | `GetLevel` | `Error` if an exception escaped or status > 499, else `Information` | | `IncludeQueryInRequestPath` | `false` - the query string is left out of `RequestPath` | | `Logger` | `null` - the static `Log.Logger` is used, with `SourceContext` `Serilog.AspNetCore.RequestLoggingMiddleware` | | `EnrichDiagnosticContext` | `null` | A 404 from a hotel search with a bad id is therefore an `Information` event, and a 503 from an overloaded availability service is an `Error`. ## Exceptions If an exception escapes the rest of the pipeline, the middleware logs the completion event at `Error` with the exception attached and `StatusCode` recorded as 500, using an exception filter that never actually catches. The exception continues to propagate, so the developer exception page or your exception handler still runs - and ASP.NET Core's own unhandled-exception event may appear as well, which the source comments acknowledge as a duplicate. ## Position in the pipeline The middleware measures and logs only what happens **after** it: - Register it early, before the middleware and endpoints you care about, so `Elapsed` covers the real work. - Middleware registered before it that ends the request itself is invisible. Placing it after `app.UseStaticFiles()` is a deliberate way to keep static file requests out of the log. - An exception handler placed before it sees exceptions after the request logger has logged them; one placed after it turns exceptions into ordinary 500 responses, which the request logger then logs at `Error` because of the status code, without the exception unless you attach it with `IDiagnosticContext.SetException`. ```csharp var app = builder.Build(); app.UseStaticFiles(); // static files: not logged app.UseSerilogRequestLogging(); // everything below is timed and logged app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/api/hotels/{id}/availability", GetAvailability); app.Run(); ``` ## Quieting the duplicates The README pairs the middleware with overrides so the framework's per-request events disappear: ```json { "Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft.AspNetCore.Hosting": "Warning", "Microsoft.AspNetCore.Mvc": "Warning", "Microsoft.AspNetCore.Routing": "Warning" } } } } ``` ## Customising the event `UseSerilogRequestLogging(options => ...)` (or `UseSerilogRequestLogging("template")` for the template alone; options registered with `services.Configure<RequestLoggingOptions>(...)` are picked up too) exposes the rest of the behaviour: - `MessageTemplate` - change the wording; the default property names stay available as holes. - `GetMessageTemplateProperties` - replace the four default properties, for example to rename them to a company-wide schema. - `IncludeQueryInRequestPath` - include the query string; leave it off when query strings can carry tokens or personal data. - `Logger` - log through a specific Serilog `ILogger` instead of the static one. ## Tuning the level Health-check probes and readiness endpoints can flood the log with successful requests. `GetLevel` receives the `HttpContext`, the elapsed milliseconds and the exception, so you can return `LogEventLevel.Verbose` for `/healthz` while keeping the defaults elsewhere, or raise slow requests to `Warning` past a threshold. Because the logger checks `IsEnabled` first, a request whose level is filtered out costs almost nothing.

  • Request logging works in development but logs nothing in production, where AddSerilog(..., preserveStaticLogger: true) is used. Why?
    `RequestLoggingOptions.Logger` defaults to null, and the middleware then writes through the static `Log.ForContext<RequestLoggingMiddleware>()`. With `preserveStaticLogger: true` the container's logger is not assigned to `Log.Logger`, so the static logger may still be silent or a bootstrap logger. Set `options.Logger` to the registered Serilog `ILogger`, or stop preserving the static logger.
  • How would you keep health-check probes out of the log without removing request logging?
    Supply `options.GetLevel` that returns `LogEventLevel.Verbose` (or `Debug`) when the request path is the probe path and falls back to the default rule otherwise. With the minimum level at Information, those events are dropped before any work, while all other requests still produce their completion event.

  • Request logging writes 4xx responses at Warning by default
  • UseSerilogRequestLogging can go at the end of the pipeline and still time every request
  • The middleware catches exceptions and turns them into 500 responses
  • The query string is included in RequestPath by default
  • Adding request logging automatically removes ASP.NET Core's own per-request events