In ASP.NET Core, how does an IHttpLoggingInterceptor change HTTP logging for each request, and what does HttpLoggingOptions.CombineLogs change about the entries?
answer
- OnRequestAsync and OnResponseAsync
- options, then endpoint, then interceptors
- Enable, Disable, TryDisable, AddParameter
- AddHttpLoggingInterceptor<T>, singleton
- one RequestResponseLog entry at the end
basics
~10 sAn IHttpLoggingInterceptor gets OnRequestAsync and OnResponseAsync callbacks with an HttpLoggingInterceptorContext to switch fields, change body limits or add parameters per request. CombineLogs writes one RequestResponseLog entry at the end instead of separate entries.
solid answer
~40 s`IHttpLoggingInterceptor` has two methods, `OnRequestAsync` and `OnResponseAsync`, both taking an `HttpLoggingInterceptorContext` and returning `ValueTask`. You register it with `services.AddHttpLoggingInterceptor<T>()` (a singleton); several run in registration order, **after** the global options and any endpoint `[HttpLogging]`/`WithHttpLogging` metadata have chosen the fields. Through the context you read `HttpContext`, change `LoggingFields` with `Enable`, `Disable` and `TryDisable`, adjust `RequestBodyLogLimit` and `ResponseBodyLogLimit`, and `AddParameter` your own key/value pairs, for instance a masked member id after taking over header logging. `CombineLogs = true` collects everything enabled into **one** `RequestResponseLog` entry (event id 9) written when the request finishes, instead of separate request, response, body and duration entries. Both arrived in ASP.NET Core 8 together with the `Duration` field.
code
csharp · 11 linesinternal sealed class SkipGetsInterceptor : IHttpLoggingInterceptor
{
public ValueTask OnRequestAsync(HttpLoggingInterceptorContext ctx)
{
if (HttpMethods.IsGet(ctx.HttpContext.Request.Method))
ctx.LoggingFields = HttpLoggingFields.None;
return default;
}
public ValueTask OnResponseAsync(HttpLoggingInterceptorContext ctx) => default;
}go deeper
Recall that an interceptor has request and response callbacks and that CombineLogs turns several HTTP log entries into one.
Explain the order options, endpoint metadata, interceptors, the context methods (Enable, Disable, TryDisable, AddParameter) and the event ids with and without CombineLogs.
Show when an interceptor is the right tool, its singleton lifetime, the response-body wrapping it forces on every request, and what CombineLogs hides for hung requests.
Decide whether per-request logging policy lives in interceptor code reviewed with the app or in shared configuration, and how teams keep one entry shape across services.
## Where interceptors fit The HTTP logging middleware decides what to log in three steps for every request: 1. **Global options**: `HttpLoggingOptions.LoggingFields` and the body limits. 2. **Endpoint metadata**: an `HttpLoggingAttribute` from `[HttpLogging(...)]` or `.WithHttpLogging(...)` replaces the fields and, if set, the limits. 3. **Interceptors**: every registered `IHttpLoggingInterceptor` runs, in registration order, and may change anything that came before. ```csharp public interface IHttpLoggingInterceptor { ValueTask OnRequestAsync(HttpLoggingInterceptorContext logContext); ValueTask OnResponseAsync(HttpLoggingInterceptorContext logContext); } ``` `OnRequestAsync` runs before the request is logged and before the endpoint executes. `OnResponseAsync` runs when the response headers are about to be logged, so the status code is known. ## What the context lets you do `HttpLoggingInterceptorContext` exposes: - `HttpContext`, to inspect the path, method, user or status; - `LoggingFields`, plus `Enable`, `Disable`, `TryDisable` (returns whether the field was on) and `IsAnyEnabled`; - `RequestBodyLogLimit` and `ResponseBodyLogLimit`; - `AddParameter(key, value)` and `Parameters`, the key/value pairs the entry will carry. `TryDisable` is the idiom for **taking over** a field: if it returns `true`, the middleware will not log that field and you add your own version. ## A claims-gateway interceptor ```csharp internal sealed class ClaimsGatewayInterceptor : IHttpLoggingInterceptor { public ValueTask OnRequestAsync(HttpLoggingInterceptorContext ctx) { if (ctx.HttpContext.Request.Path.StartsWithSegments("/health")) { ctx.LoggingFields = HttpLoggingFields.None; // nothing for probes return default; } if (ctx.TryDisable(HttpLoggingFields.RequestHeaders) && ctx.HttpContext.Request.Headers.TryGetValue("X-Member-Id", out var id)) { var value = id.ToString(); ctx.AddParameter("MemberIdSuffix", value.Length > 4 ? value[^4..] : "****"); } return default; } public ValueTask OnResponseAsync(HttpLoggingInterceptorContext ctx) { if (ctx.HttpContext.Response.StatusCode < 500) ctx.Disable(HttpLoggingFields.ResponseBody); // bodies only for 5xx return default; } } builder.Services.AddHttpLogging(o => { o.LoggingFields = HttpLoggingFields.RequestPropertiesAndHeaders | HttpLoggingFields.ResponsePropertiesAndHeaders | HttpLoggingFields.ResponseBody | HttpLoggingFields.Duration; o.CombineLogs = true; }); builder.Services.AddHttpLoggingInterceptor<ClaimsGatewayInterceptor>(); ``` Here every request header is dropped and replaced by the last four characters of the member id, health probes produce no entries, and the response body, enabled globally, is kept only for server errors. ## The price of an interceptor - `AddHttpLoggingInterceptor<T>` registers the type as a **singleton** with `TryAddEnumerable`; it must be thread-safe and must not capture scoped services. - With any interceptor registered, the middleware runs even for endpoints whose fields are `None`, because an interceptor could turn fields back on. - It also wraps the response body stream on **every** request, in case an interceptor decides late to log the body. That wrapper costs something even when no body is ever logged. ## CombineLogs By default each piece is written as soon as it is known: | Event id | Name | When | |---|---|---| | 1 | `RequestLog` | before the endpoint runs | | 3 | `RequestBody` | when the body has been read or hit its limit | | 2 | `ResponseLog` | when response headers are written | | 4 | `ResponseBody` | at the end | | 8 | `Duration` | at the end | With `CombineLogs = true`, the middleware accumulates request properties, headers, `RequestBody` with `RequestBodyStatus`, response properties, `ResponseBody` and `Duration` into **one** entry, `RequestResponseLog` (9), written after the response finishes. Trade-offs: - one entry per request is easier to query and cheaper to index; - a request that hangs, streams for minutes or dies with the process produces nothing until it ends, whereas separate entries would at least show the request arrived; - interceptors still get the final say, because bodies are added only if their fields are still enabled after `OnResponseAsync`. `AddHttpLoggingRedaction` from dotnet/extensions turns `CombineLogs` on for you.
- Why must an IHttpLoggingInterceptor not depend on a scoped service such as a DbContext?`AddHttpLoggingInterceptor<T>` registers it as a singleton, and the middleware receives all interceptors once in its constructor. A scoped dependency would be captured for the life of the app, shared across concurrent requests. Resolve per-request services from `ctx.HttpContext.RequestServices` inside the callback if one is really needed.
- With CombineLogs on, an operator sees no HTTP log for a request that timed out at the load balancer. Why?The combined `RequestResponseLog` entry is written only when the middleware's `finally` block runs at the end of the request. If the handler is still running, or the process dies, the entry never appears. Without `CombineLogs`, the `RequestLog` entry would have been written before the endpoint ran.
- Interceptors run before endpoint [HttpLogging] metadata, so the attribute wins.
- AddHttpLoggingInterceptor registers the interceptor per request, so scoped services are fine.
- CombineLogs merges entries in the logging provider after they are written.
- With CombineLogs on, the request line is still written before the endpoint runs.
- Registering an interceptor costs nothing for requests it ignores.
Assumes ASP.NET Core 10; IHttpLoggingInterceptor, CombineLogs and HttpLoggingFields.Duration were introduced in ASP.NET Core 8 and work the same way in 10, so guides written for 6 or 7 show none of them.