5.14 — Request/Response Logging Middleware¶
← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.13 Middleware vs filters · Next: 6.1 IoC and DI
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Request logging middleware records what came in and what went out — path, method, status, duration — for every request.
- It belongs in middleware, not a filter, so it also sees 404s, static files and rejected requests.
- ASP.NET Core has
UseHttpLogging()built in. Try it before writing your own. - ⚠️ Logging bodies and headers leaks credentials. That is the real risk in this topic.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Request logging | a cross-cutting concern | Recording each request's method, path, status and duration. |
UseHttpLogging() |
a middleware method | The built-in logger. Configurable via AddHttpLogging. |
HttpLoggingFields |
an enum, flags | Which parts to log — request path, headers, body, response status, and so on. |
| Structured logging | a logging style | Logging named fields rather than an interpolated string, so they can be queried. |
| Message template | a log format string | "{Method} {Path}" with values passed separately. Keeps fields queryable. |
| Log scope | a logging feature | Attaches properties to every log entry written inside a block. BeginScope. |
| Correlation ID | a tracing value | An identifier shared across services for one logical operation. |
| Sampling | a volume-control technique | Logging a percentage of requests rather than all of them. |
| Redaction | a safety technique | Replacing sensitive values with a placeholder before logging. |
W3CLogger |
built-in middleware | Writes access logs in the standard W3C format to a file. |
The concept¶
Why it is middleware, not a filter¶
A filter only runs when routing matched an action (5.13). So a filter-based logger silently misses:
- 404s — no action matched, so no filter ran
- Static files — served and short-circuited before the endpoint
- Rejected requests — rate limited, failed authentication, blocked by CORS
- Exceptions in earlier middleware
Those are exactly the requests you most want when investigating a problem. Request logging belongs in middleware, registered early.
⚠️ The thing that actually matters here¶
Before any of the mechanics: request logging is the most common way applications leak credentials into their logs.
Headers contain Authorization: Bearer eyJ... and Cookie: session=.... Bodies contain
passwords, card numbers and personal data. Query strings contain API keys and reset tokens.
Log those wholesale and you have written every secret your application handles into a system that is widely readable inside your company and retained for months. It is also a data-protection problem — under GDPR and similar rules, personal data in logs is personal data you are processing and must justify, secure and eventually delete.
A picture: a security camera pointed at the keypad. Recording who enters is sensible. Recording the code they typed is a liability.
Default to logging metadata, not content.
How it works¶
The simple version — use the built-in one first¶
builder.Services.AddHttpLogging(options =>
{
options.LoggingFields =
HttpLoggingFields.RequestMethod |
HttpLoggingFields.RequestPath |
HttpLoggingFields.RequestQuery |
HttpLoggingFields.ResponseStatusCode |
HttpLoggingFields.Duration;
// Headers are NOT logged unless explicitly allowed — a good default
options.RequestHeaders.Add("X-Correlation-Id");
options.ResponseHeaders.Add("X-Correlation-Id");
});
var app = builder.Build();
app.UseHttpLogging(); // early, so it sees everything
⚠️ Note what is absent: no RequestBody or ResponseBody. Those fields exist, and the
framework deliberately makes you opt in per header and per body because of the leak risk.
By default UseHttpLogging logs at Information, which is very high volume on a busy service.
Adjust it:
{
"Logging": {
"LogLevel": {
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Warning"
}
}
}
How it actually works — writing your own¶
You write your own when you need a specific shape, sampling, or enrichment the built-in one does not provide:
internal class RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
var start = Stopwatch.GetTimestamp();
try
{
await next(context);
}
finally
{
// finally, so we log even when an exception propagates
var elapsed = Stopwatch.GetElapsedTime(start);
// Level depends on outcome — 5xx is our problem, 4xx is theirs
var level = context.Response.StatusCode switch
{
>= 500 => LogLevel.Error,
>= 400 => LogLevel.Warning,
_ when elapsed.TotalMilliseconds > 1000 => LogLevel.Warning, // slow
_ => LogLevel.Information
};
logger.Log(level,
"{Method} {Path} responded {StatusCode} in {ElapsedMs:0.0}ms",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
elapsed.TotalMilliseconds);
}
}
}
Three deliberate choices:
finally — so a request that throws is still logged. Without it, the requests that failed
are exactly the ones missing from your logs.
Level varies by outcome — if everything logs at Information, the level conveys nothing and
you cannot alert on errors. A slow request also gets promoted to Warning, which is how you
notice degradation before users complain.
A message template, not interpolation:
// ✗ One opaque string. You cannot query or aggregate it.
logger.LogInformation($"{method} {path} took {ms}ms");
// ✓ Named fields, queryable in your log system
logger.LogInformation("{Method} {Path} took {Ms}ms", method, path, ms);
That difference is what makes structured logging useful — you can ask "show me all requests to
/api/orders slower than 2 seconds", which is impossible with pre-formatted strings. See
18.1.
Correlation IDs and scopes¶
Better than logging fields per entry: put them in a scope so everything downstream inherits them.
internal class RequestContextLoggingMiddleware(
RequestDelegate next,
ILogger<RequestContextLoggingMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
var correlationId = context.Request.Headers["X-Correlation-Id"].FirstOrDefault()
?? context.TraceIdentifier;
using (logger.BeginScope(new Dictionary<string, object>
{
["CorrelationId"] = correlationId,
["UserId"] = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"
}))
{
await next(context);
}
}
}
Now every log line written anywhere in that request — in a controller, a service, EF Core — carries the correlation ID and user, with no extra code. Searching one ID reconstructs the whole request, and if the ID came from an upstream service, across services too. See 18.4.
The deeper detail — volume and cost¶
On a service handling 1,000 requests per second, logging every request at Information produces
86 million entries a day. That has real consequences: ingestion cost in your log platform,
storage, and slower queries when you actually need to search.
Three ways to control it:
Sample the successful ones:
var shouldLog =
context.Response.StatusCode >= 400 || // always log failures
elapsed.TotalMilliseconds > 500 || // always log slow ones
Random.Shared.Next(100) < 5; // 5% of the rest
Exclude noise:
if (context.Request.Path.StartsWithSegments("/healthz"))
{
await next(context);
return; // health probes every 5s would dominate your logs
}
Raise the level of the built-in loggers in configuration, so framework chatter does not drown your own entries:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
That EF Core line is worth knowing — at Information it logs every SQL statement, which is
useful in development and overwhelming in production.
If you must log bodies¶
Covered fully in 5.9, but the safety rules:
private static readonly string[] SensitiveKeys =
["password", "token", "secret", "apiKey", "cardNumber", "ssn", "authorization"];
- Buffer selectively — by path, content type and size, never globally
- Cap the size, so a large upload cannot force a large allocation
- Log only on failure, which keeps volume manageable and diagnostic value high
- Redact known sensitive fields, and log nothing rather than raw bytes if parsing fails
- Gate the whole thing behind a config flag so it can be turned on and off without a deploy
Code¶
A production-shaped logger combining the above:
internal class RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
private static readonly PathString[] Excluded =
[new("/healthz"), new("/ready"), new("/metrics")];
public async Task InvokeAsync(HttpContext context)
{
// Skip high-frequency infrastructure endpoints entirely
if (Excluded.Any(p => context.Request.Path.StartsWithSegments(p)))
{
await next(context);
return;
}
var correlationId = context.Request.Headers["X-Correlation-Id"].FirstOrDefault()
?? context.TraceIdentifier;
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Correlation-Id"] = correlationId;
return Task.CompletedTask;
});
using var scope = logger.BeginScope(new Dictionary<string, object>
{
["CorrelationId"] = correlationId,
["UserId"] = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous",
["ClientIp"] = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"
});
var start = Stopwatch.GetTimestamp();
try
{
await next(context);
}
finally
{
var elapsed = Stopwatch.GetElapsedTime(start);
var status = context.Response.StatusCode;
var level = status switch
{
>= 500 => LogLevel.Error,
>= 400 => LogLevel.Warning,
_ when elapsed.TotalMilliseconds > 1000 => LogLevel.Warning,
_ => LogLevel.Information
};
logger.Log(level,
"HTTP {Method} {Path} → {StatusCode} in {ElapsedMs:0.0}ms",
context.Request.Method,
context.Request.Path, // note: Path, NOT QueryString — see traps
status,
elapsed.TotalMilliseconds);
}
}
}
⚠️ Request.Path is logged, not Request.QueryString. Query strings routinely carry API
keys, password-reset tokens and email addresses. If you need query parameters, log a specific
allow-list of them rather than the whole string.
Interview questions¶
Q: Should request logging be middleware or a filter?
Middleware, registered early. A filter only runs when routing matched an action, so it silently misses 404s, static file requests, and anything rejected upstream by rate limiting or authentication — which are exactly the requests you want when investigating a problem. Middleware sees everything that reaches it, and putting it near the top of the pipeline means it covers the whole request.
Q: What is the main risk with request logging?
Leaking credentials and personal data. Headers carry Authorization and Cookie, bodies carry
passwords and card numbers, and query strings often carry API keys and reset tokens. Logging
those wholesale writes every secret the application handles into a system that is widely
readable and retained for months, and under data-protection rules personal data in logs is data
you are processing and must justify. So I default to logging metadata — method, path, status,
duration — and treat headers and bodies as opt-in with redaction.
Q: Why use a message template instead of string interpolation?
Because structured logging keeps the values as named, queryable fields. Writing
logger.LogInformation("{Method} {Path} took {Ms}ms", method, path, ms) lets your log platform
index those properties, so you can ask for all requests to a specific path slower than two
seconds. With interpolation you get one opaque string per entry and no way to aggregate. It also
allows the logging framework to skip formatting entirely when that level is disabled.
Q: How do you control log volume?
Three things. Exclude high-frequency infrastructure endpoints like health probes, which
otherwise dominate the output since orchestrators poll every few seconds. Sample the successful
requests — always log failures and slow requests, and a small percentage of the rest. And raise
the level of noisy framework loggers in configuration, particularly
Microsoft.EntityFrameworkCore.Database.Command, which logs every SQL statement at Information
level. At a thousand requests a second, logging everything is around eighty-six million entries
a day, which costs real money and makes searching slower when you need it.
Traps ⚠️¶
- Logging in a filter misses 404s, static files and rejected requests.
- Logging headers leaks
AuthorizationandCookievalues. - Logging query strings leaks API keys and reset tokens. Log
Path, notQueryString. - Logging without
finallymeans failed requests — the important ones — are missing. - Everything at
Informationmakes the level meaningless and prevents alerting. - String interpolation instead of a message template destroys queryability.
- Health check endpoints dominate the logs unless excluded.
- EF Core logs every SQL statement at
Information. Raise it in production. - Buffering bodies for every request costs memory or disk on every request (5.9).
Related¶
- 5.9 Request body buffering — reading bodies safely
- 5.13 Middleware vs filters — why this is middleware
- 5.8 HttpContext —
OnStartingandTraceIdentifier - 5.10 Built-in middleware —
UseHttpLogging - 18.1 ILogger and levels — structured logging
- 18.4 Scopes and correlation IDs —
BeginScope - 18.10 What not to log — the redaction rules
- 18.7 OpenTelemetry — tracing across services