skip to content

In ASP.NET Core HTTP logging, what does enabling RequestBody and ResponseBody cost, and how do the body log limits, MediaTypeOptions and WithHttpLogging contain it?

level: seniorimportance: should knowfreq 34%

answer

  1. copied as the app reads, not read ahead
  2. 32 KB per direction by default
  3. text media types only
  4. [Truncated by RequestBodyLogLimit]
  5. endpoint fields replace the global set

basics

~20 s

Body logging wraps both streams and copies up to 32 KB of each, for JSON, XML and text/* types only, into Information entries. That costs buffers, decoding and large entries per request; WithHttpLogging or [HttpLogging] narrows it per endpoint.

solid answer

~40 s

With `RequestBody` on, the middleware swaps `Request.Body` for a buffering stream that copies bytes **as the endpoint reads them**, up to `RequestBodyLogLimit` (default 32 KB), and logs the text with a status such as `[Truncated by RequestBodyLogLimit]` or `[Not consumed by app]`. `ResponseBody` swaps the response body feature the same way, up to `ResponseBodyLogLimit` (also 32 KB). Only content types listed in `MediaTypeOptions` are logged, by default `application/json`, `application/*+json`, `application/xml`, `application/*+xml` and `text/*`; anything else gets a Debug note instead. The cost is per request: buffer copies, string decoding, entries up to 32 KB each, and every body field becomes data you must protect. `WithHttpLogging(fields, requestBodyLogLimit, responseBodyLogLimit)` on a Minimal API endpoint, or `[HttpLogging]` on a controller, **replaces** the global `LoggingFields` for that endpoint, so bodies can stay off globally and on where needed.

code

csharp · 9 lines
csharp
[HttpLogging(HttpLoggingFields.RequestPropertiesAndHeaders | HttpLoggingFields.RequestBody,
             RequestBodyLogLimit = 2048)]
[ApiController]
[Route("partner-callbacks")]
public sealed class PartnerCallbacksController : ControllerBase
{
    [HttpPost]
    public IActionResult Receive(CallbackPayload payload) => Accepted();
}

go deeper

for a junior

Recall that bodies are off by default, that RequestBody and ResponseBody turn them on, and that each is cut at a limit.

for a middle

Explain the 32 KB limits, the text-only media types, the body status suffixes and how WithHttpLogging or [HttpLogging] override the global fields.

for a senior

Show how you contain the cost and the privacy exposure: bodies only on named endpoints, low limits, a time box, and reading the status suffixes correctly.

for a principal

Set the policy for when production bodies may be logged at all, who approves it, and how long such logs may be kept.

## How bodies are captured Bodies are opt-in: `HttpLoggingFields.RequestBody` and `ResponseBody`, or the composites `Request`, `Response` and `All`, which include them. **Request body.** The middleware never reads the body itself. When the request's `Content-Type` maps to a text encoding, it replaces `HttpContext.Request.Body` with a buffering stream. As the endpoint (or model binding) reads, the wrapper copies the bytes it returns into a buffer until `RequestBodyLogLimit` bytes have been seen. The entry, event `RequestBody` (3), carries the decoded text and a status: | Status | Meaning | |---|---| | (empty) | the app read the whole body within the limit | | `[Truncated by RequestBodyLogLimit]` | the limit was reached; the rest was not logged | | `[Only partially consumed by app]` | the endpoint stopped reading early | | `[Not consumed by app]` | the endpoint never read the body | **Response body.** The middleware replaces `IHttpResponseBodyFeature` with a buffering wrapper that passes writes through to the client while copying up to `ResponseBodyLogLimit` bytes, logged as `ResponseBody` (4). ## The defaults - `RequestBodyLogLimit` = `ResponseBodyLogLimit` = 32 KB (`32 * 1024`). - `MediaTypeOptions` starts with `application/json`, `application/*+json`, `application/xml`, `application/*+xml` and `text/*`, all decoded as UTF-8; `AddText` adds a type, `Clear` empties the list. - A body with an unlisted type is not logged: the middleware writes a Debug-level "Unrecognized Content-Type" entry instead, or "No Content-Type header" when the header is missing. - `MediaTypeOptions.AddBinary` exists but throws `NotSupportedException`: binary bodies cannot be logged. ## What it costs The documentation says plainly that HTTP logging can reduce performance, especially with bodies. On every logged request: 1. the wrapper copies up to 32 KB per direction into buffers it allocates; 2. the bytes are decoded into a string; 3. a log entry of up to 32 KB is formatted, queued and shipped by each provider, then stored and indexed downstream; 4. the body becomes part of the log store's attack surface. In a health-insurance claims gateway, a `POST /claims` body carries diagnosis codes and member details; once logged, every log reader and every log export holds them. A single busy endpoint can produce more log volume from bodies than the rest of the app produces altogether. ## Narrowing it per endpoint Global options are the default; endpoint metadata overrides them: ```csharp builder.Services.AddHttpLogging(o => o.LoggingFields = HttpLoggingFields.RequestPropertiesAndHeaders | HttpLoggingFields.ResponseStatusCode); app.MapPost("/claims", SubmitClaim); // global fields: no bodies app.MapGet("/eligibility/{planCode}", CheckEligibility) .WithHttpLogging(HttpLoggingFields.ResponsePropertiesAndHeaders | HttpLoggingFields.ResponseBody, responseBodyLogLimit: 4096); ``` - `WithHttpLogging<TBuilder>(HttpLoggingFields loggingFields, int? requestBodyLogLimit = null, int? responseBodyLogLimit = null)` adds an `HttpLoggingAttribute` to the endpoint's metadata; it works on single endpoints and route groups. - `[HttpLogging(HttpLoggingFields.RequestHeaders, RequestBodyLogLimit = 1024)]` does the same on a controller or action. - The endpoint's fields **replace** the global `LoggingFields`; they are not merged. A limit passed here overrides the global limit only when it is set. - `HttpLoggingFields.None` on an endpoint switches logging off for it, unless an interceptor turns fields back on. ## Practical rules - Keep bodies off globally; turn them on for a named endpoint, a short time and a stated reason. - Lower the limits to what the investigation needs; a few KB usually show the shape of a payload. - Remember the status suffixes when reading entries: a `[Not consumed by app]` request body is empty because the endpoint never read it, not because the client sent nothing.

  • A logged request body shows [Not consumed by app] although the client sent JSON. What happened?
    The middleware only records bytes the app reads through the wrapped `Request.Body`. The endpoint never read the body, for example because it rejected the request first or returned early, so nothing passed through the wrapper. It is a statement about the app, not about the client.
  • Why would a large file-upload endpoint still log no body with RequestBody enabled globally?
    Bodies are only logged for content types listed in `MediaTypeOptions`, which hold JSON, XML and `text/*` by default. An `application/octet-stream` or `multipart/form-data` upload is skipped with a Debug "Unrecognized Content-Type" entry, and `AddBinary` cannot change that because it throws `NotSupportedException`.

  • The middleware reads the whole request body up front before the endpoint runs.
  • Bodies larger than the limit are skipped entirely rather than truncated.
  • WithHttpLogging fields are merged with the global LoggingFields.
  • Calling MediaTypeOptions.AddBinary lets you log binary uploads.
  • Body logging is free once the bytes are already in memory.