LESSON 6 OF 12

6. Request Logging and the HTTP Request Lifecycle

Learn how to record HTTP requests as single Serilog events, filter health and noisy endpoints, add custom request enrichment, and test middleware ordering.

45 dk 64

Introduction

In the previous lessons, we configured Serilog, discussed structured logging, reviewed sink options, and introduced centralized logging. This lesson focuses on making the lifecycle of an HTTP request visible through one meaningful log event.

A traditional implementation may write one log at the beginning of a request, several logs inside a controller, and another log when the response is completed. Although this can work, it increases log volume and makes it harder to connect records that belong to the same request. The UseSerilogRequestLogging() middleware provided by Serilog.AspNetCore collects request completion information such as the HTTP method, path, status code, and elapsed time in one event.

By the end of this lesson, you will configure request logging in an ASP.NET Core API, filter health and noisy paths, add custom diagnostic properties, and test how middleware ordering changes the result.

The HTTP request lifecycle

In ASP.NET Core, a request moves through the middleware pipeline defined in Program.cs. Middleware components run in the order in which they are added for the request path, and response processing unwinds in reverse order. Therefore, the position of a middleware determines both what it can observe and whether it can produce a completion event for a request.

A simplified flow looks like this:

  1. The client sends an HTTP request.
  2. Serilog request logging starts its timer.
  3. Routing, authentication, authorization, and endpoint middleware execute.
  4. A controller, minimal API endpoint, or health check generates a response.
  5. Response middleware completes in reverse order.
  6. Serilog request logging records the status code and elapsed time.

When request logging is placed before the endpoint components, it can observe the downstream endpoint result. However, a component that short-circuits the pipeline before request logging is reached may not be included in the request log. This distinction matters for static files, health checks, authentication, and exception handling.

Adding Serilog request logging

Verify the package

If Serilog.AspNetCore is not already installed, add it with the following command. If it was configured in an earlier lesson, you do not need to repeat this step.

dotnet add package Serilog.AspNetCore

The following example assumes that the Serilog logger from the previous lessons is already configured. The important detail here is Enrich.FromLogContext(), which allows request-scoped diagnostic properties to flow into log events.

using Serilog;
using Serilog.Events;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((context, services, configuration) =>
{
    configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext()
        .WriteTo.Console();
});

builder.Services.AddHealthChecks();
builder.Services.AddControllers();

var app = builder.Build();

Basic request logging configuration

For the basic scenario, add the middleware before mapping the endpoints.

app.UseSerilogRequestLogging();

app.MapControllers();
app.MapHealthChecks("/healthz");

app.Run();

The default request completion event normally contains properties such as RequestMethod, RequestPath, StatusCode, and Elapsed. An example message is:

HTTP GET /api/orders responded 200 in 37.4210 ms

This single event makes it easy to determine whether a request succeeded and how long it took. Detailed application events can still be written inside endpoints or services, but producing separate start and finish events for every request is often unnecessary.

Customizing the message template and level

You can change the request completion message and its level through RequestLoggingOptions.

app.UseSerilogRequestLogging(options =>
{
    options.MessageTemplate =
        "HTTP {RequestMethod} {RequestPath} => {StatusCode} in {Elapsed:0.000} ms";

    options.GetLevel = (httpContext, elapsed, exception) =>
    {
        if (exception != null)
            return LogEventLevel.Error;

        if (httpContext.Response.StatusCode >= 500)
            return LogEventLevel.Error;

        if (elapsed > 1000)
            return LogEventLevel.Warning;

        return LogEventLevel.Information;
    };
});

The elapsed value is expressed in milliseconds. Promoting slow requests to Warning is a useful starting point, but the threshold should be based on the normal response-time profile of your application. If every slow request is logged as Error, the visibility of genuine failures can be reduced.

Custom request enrichment

The default properties may not be enough for every application. You can add the host, scheme, endpoint name, user identifier, or correlation ID to the request completion event.

app.UseSerilogRequestLogging(options =>
{
    options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
    {
        diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
        diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
        diagnosticContext.Set("ClientIp", httpContext.Connection.RemoteIpAddress?.ToString());
        diagnosticContext.Set("EndpointName", httpContext.GetEndpoint()?.DisplayName);

        if (httpContext.Request.Headers.TryGetValue("X-Correlation-Id", out var correlationId))
        {
            diagnosticContext.Set("CorrelationId", correlationId.ToString());
        }
    };
});

This callback runs for the request completion event. Be careful when adding a username or tenant value: do not place sensitive personal data directly in logs. Mask the value when necessary or use a technical subject identifier instead.

To add operation-specific information from an endpoint to the request completion event, use IDiagnosticContext:

app.MapGet("/api/catalog", (IDiagnosticContext diagnosticContext) =>
{
    var itemCount = 42;
    diagnosticContext.Set("CatalogItemCount", itemCount);
    diagnosticContext.Set("CacheHit", true);

    return Results.Ok(new { itemCount });
});

Depending on the Serilog.AspNetCore version used by your project, your IDE may resolve IDiagnosticContext from a different namespace. Use the namespace suggested by the installed package. The important part is that the service is resolved through dependency injection. The CatalogItemCount and CacheHit values are then attached to the request completion event instead of being emitted as separate events.

Filtering health and noisy endpoints

A load balancer, Kubernetes, or monitoring system may call /healthz frequently. Writing every probe at Information level can unnecessarily increase production log volume. You can lower the level or exclude these requests through GetLevel.

app.UseSerilogRequestLogging(options =>
{
    options.GetLevel = (httpContext, elapsed, exception) =>
    {
        var path = httpContext.Request.Path;

        if (path.StartsWithSegments("/healthz") && exception == null)
            return LogEventLevel.Debug;

        if (exception != null || httpContext.Response.StatusCode >= 500)
            return LogEventLevel.Error;

        return LogEventLevel.Information;
    };
});

Using Debug for health endpoints is often safer than dropping them completely. You can temporarily enable Debug logging when you need to investigate probe behavior. The same strategy can be applied to static files, favicon requests, or monitoring paths.

If you decide to suppress an endpoint entirely, first consider the operational trade-off. Health logs may be unnecessary when probe failures are monitored separately, but they can still be useful for diagnosing deployment or infrastructure issues.

Testing middleware ordering

To observe ordering, try two different pipeline arrangements. In the first arrangement, request logging runs before routing and endpoints:

app.UseSerilogRequestLogging();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

With this arrangement, response results produced by controllers and authorization are visible in the request completion event. For example, a 401 or 403 response caused by authorization should appear in the request event.

Next, move request logging into a branch that only handles selected paths:

app.UseWhen(
    context => context.Request.Path.StartsWithSegments("/api"),
    branch =>
    {
        branch.UseSerilogRequestLogging();
    });

app.MapControllers();
app.MapHealthChecks("/healthz");

In this case, endpoints that do not begin with /api may not have the same request logging behavior. Call /healthz and verify whether it is logged so that you can confirm the branch behavior.

The position of exception handling relative to request logging also changes the result. When request logging can observe an exception, the event may be written at Error level. If exception handling catches the exception and converts it into a 500 response, the request event may still show status code 500, but whether an exception property is present depends on the middleware arrangement and how the error is handled.

Test scenarios

  1. Successful request: Call GET /api/catalog. Verify the method, path, 200 status code, and elapsed value.
  2. Missing endpoint: Call a random path and confirm that a 404 request event is produced.
  3. Unauthorized request: Access an authorized endpoint without a token. Inspect whether the 401 or 403 result appears in the request event.
  4. Slow request: Add a short delay to a test endpoint. Confirm that the elapsed value crosses the configured threshold.
  5. Exception: Produce a controlled test exception. Verify the Error level and the response status code.
  6. Health probe: Call GET /healthz. Confirm that the event is written at Debug rather than Information according to the rule.

You can inspect the first results with the console sink and then use Seq to filter by StatusCode, RequestPath, Elapsed, or CorrelationId.

Common mistakes

  • Adding the middleware too late: Placing request logging inside a single endpoint branch can cause other requests to disappear from the request log.
  • Writing request logs in every layer: Repeating start and finish events in controllers, services, and middleware increases volume. Produce the completion event from one central location.
  • Logging query strings and sensitive headers without review: Never record tokens, passwords, or personal data. Include query strings only when their contents are known to be safe.
  • Leaving health endpoints at Information: Frequent probes can create unnecessary noise and increase storage costs.
  • Misreading elapsed time: The value is in milliseconds. Network delays, downstream calls, and internal waits can all contribute to it.
  • Equating exceptions with status codes: Not every 500 response has the same root cause. Analyze request events together with exception logs and traces.
  • Forgetting sink level filters: Even if GetLevel returns Debug, the event will not appear if the sink or minimum level rejects Debug events.

Practice exercise

Apply the following requirements to the API project:

  1. Add UseSerilogRequestLogging before the endpoint mappings.
  2. Add RequestHost, EndpointName, and the existing X-Correlation-Id as enrichment properties.
  3. Lower /healthz requests to Debug level.
  4. Write requests longer than 1000 milliseconds at Warning level.
  5. Set a ResultCount property through IDiagnosticContext inside one endpoint.
  6. Collect sample output for successful, 404, 500, slow, and health requests.

Summary

Serilog request logging middleware turns the HTTP request lifecycle into one operationally meaningful completion event. Method, path, status code, and elapsed time are the core fields, while EnrichDiagnosticContext adds application-specific context. With GetLevel, failures and slow requests can be promoted while health and noisy endpoints can be kept at a lower level.

Middleware ordering is the most important implementation detail. The position in the pipeline determines which requests are observed, whether endpoint information is available, and how short-circuited responses are recorded. In the next step, these request events can be combined with correlation IDs and distributed tracing data so that a single request can be followed across multiple services.

Sources