Skip to main content

ContextLoggingMiddleware

Namespace: RA.Utilities.Api.Middlewares

The ContextLoggingMiddleware enriches every log entry within a request's lifetime with the X-Request-Id correlation identifier. By establishing a logging scope at the very beginning of the pipeline, it ensures that all downstream log entries — from application code, other middlewares, or framework internals — automatically carry the request's identity.

This makes it trivial to correlate all log entries belonging to a single request, even across multiple services, by filtering on the X-Request-Id value in your logging platform.

Renamed in v10.2.1

This middleware was previously named RequestContextLoggingMiddleware. The Use extension method was renamed with it — UseContextLoggingMiddleware() — while AddRequestContextLoggingMiddleware() kept its name. Only code that calls the old Use method or references the middleware type directly needs updating. See the migration guide for details.

caution

Do not use ContextLoggingMiddleware if you are already using LoggingMiddleware. The LoggingMiddleware already enriches log entries with request-scoped context — it creates a logging scope containing the x-request-id correlation ID for every request it processes.

Adding ContextLoggingMiddleware on top of it is redundant and adds unnecessary overhead.

Key Features​

  1. Automatic Log Enrichment: Wraps the entire downstream pipeline in an ILogger.BeginScope call, so every ILogger call within the request automatically includes the X-Request-Id.

  2. Zero Configuration: No options class, no setup callbacks — register and use. The middleware reads the X-Request-Id header from the incoming request, or falls back to HttpContext.TraceIdentifier if missing, via CommonUtilities.GetRequestId(context).

  3. Plays Well with Others: Designed to sit at the very start of the middleware pipeline so that DefaultHeadersMiddleware — and your own code — share the same enriched log scope. Do not combine it with LoggingMiddleware; that middleware already creates its own request scope.

🚀 Usage Guide​

Step 1: Register the middleware services in Program.cs​

Call AddRequestContextLoggingMiddleware() — no options are needed.

// Program.cs
using RA.Utilities.Api.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestContextLoggingMiddleware();

var app = builder.Build();

Step 2: Add the middleware to the pipeline​

Place app.UseContextLoggingMiddleware() first in the pipeline, before any other middleware that produces log output.

// Program.cs (continued)

app.UseContextLoggingMiddleware();

app.UseDefaultHeadersMiddleware();

app.MapControllers();

app.Run();

If you need structured request/response logging, use LoggingMiddleware instead of this middleware — it creates its own request scope and adding both is redundant.

How It Works​

For every incoming request, the middleware:

  1. Reads the X-Request-Id header from the request (falling back to HttpContext.TraceIdentifier if absent)
  2. Opens a logging scope with the key x-request-id set to that value, plus TraceId set to HttpContext.TraceIdentifier
  3. Invokes the rest of the pipeline inside that scope

Any ILogger call made during the request — in your controllers, services, or other middlewares — will include both properties:

{
"@timestamp": "2026-08-07T12:34:56.789Z",
"level": "Information",
"message": "Processing order #42",
"x-request-id": "abc-123-def-456",
"TraceId": "0HN7GVK3M9Q8U:00000001"
}

Combining with Other Middlewares​

The recommended pipeline order places ContextLoggingMiddleware first so subsequent middlewares inherit its scope:

app.UseContextLoggingMiddleware(); // ← enriches log scope
app.UseDefaultHeadersMiddleware(); // ← validates headers

If you need HTTP request/response logging, register LoggingMiddleware instead of ContextLoggingMiddleware; it already enriches the scope it creates.