CSharpEssentials.RequestResponseLogging
Middleware that logs HTTP requests and responses (bodies, headers, path, method, timing, sizes). Configured on IApplicationBuilder; no service registration is needed.
Installation
dotnet add package CSharpEssentials.RequestResponseLogging
Namespace
using CSharpEssentials.RequestResponseLogging;
Register
AddRequestResponseLogging is an IApplicationBuilder extension that adds the middleware. Call it on the built app.
var app = builder.Build();
app.AddRequestResponseLogging(opt =>
{
opt.UseLogger(app.Services.GetRequiredService<ILoggerFactory>(), LoggingOptions.CreateAllFields());
opt.IgnorePaths("/health", "/metrics");
});
- Without
UseLoggerorUseHandler, the middleware runs but writes nothing. IgnorePathsmatches by prefix, ignoring case and a trailing/("/health"also skips/healthz)."/"skips only the root path. A later call replaces the earlier list.- Without a handler, the request body is read only when
LoggingFieldshasRequestorRequestLength, the response body only when it hasResponseorResponseLength. With a handler both are captured. - A request with a
Content-Lengthover 10 MB is not read (Request body too large: {n} bytes); a chunked body is read up to 10 MB, then logged asRequest body too large: over 10485760 bytes. An empty body is logged asEmpty request body. - Each response write goes to the client right away and is also copied into memory, so streaming still works, but the whole response body is held in memory until the request finishes. Use
[SkipResponseLogging]on very large responses. Set status and headers before the first write. - If the pipeline throws, the middleware logs the captured request body with
Exception: {type}, Message: {message}as the response body, passes the same context to theUseHandlerhandler, then rethrows. UseHandlerruns in addition toUseLoggerwhen both are set.
Choosing fields
app.AddRequestResponseLogging(opt =>
opt.UseLogger(app.Services.GetRequiredService<ILoggerFactory>(), logging =>
{
logging.LoggingFields = [LogFields.Method, LogFields.Path, LogFields.ResponseTiming];
logging.HeaderKeys = ["X-Correlation-Id"];
logging.LoggingLevel = LogLevel.Debug;
logging.LoggerCategoryName = "Http";
}));
LogFields: Request, Response, HostName, Path, Method, QueryString, Headers, ResponseTiming, RequestLength, ResponseLength. LoggingOptions.CreateAllFields() selects all of them; the default list is empty.
- The
Headersfield writes only the request headers inHeaderKeys([{"X-Correlation-Id":"..."}],[]when none is present); with no keys it is empty, so credentials are not logged by default. Names are compared case-sensitively with the spelling received: standard names are normalized by Kestrel, a custom header must match as sent (HTTP/2 sends lower-case). Uselogging.HeaderKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "X-Correlation-Id" }to ignore the case. UseSeparateContext(defaulttrue) writes one named placeholder per field ({Path},{Method}) for structured logging providers;falsewrites one formatted text.LoggingLeveldefaults toInformationandLoggerCategoryNametoRequestResponseLogger.RequestLengthandResponseLengthcount characters of the logged text, not bytes; a request without a body reports the 18 characters ofEmpty request body.
Custom handler
app.AddRequestResponseLogging(opt => opt.UseHandler(context =>
{
Console.WriteLine($"{context.Url} {context.ResponseTime} {context.RequestLength} {context.ResponseLength}");
return Task.CompletedTask;
}));
RequestResponseContext exposes RequestBody, ResponseBody, ResponseCreationTime (TimeSpan?), ResponseTime (mm:ss.fff text), RequestLength, ResponseLength and Url. The handler runs after the rest of the pipeline has completed or thrown.
Per-endpoint opt-out
The middleware reads the attributes from endpoint metadata:
| Attribute | Effect |
|---|---|
| [SkipRequestLogging] | Request body is not captured |
| [SkipResponseLogging] | Response body is not captured |
| [SkipRequestResponseLogging] | Neither body is captured |
[ApiController]
[Route("auth")]
public sealed class AuthController : ControllerBase
{
[HttpPost("login")]
[SkipRequestLogging] // passwords
public IActionResult Login(LoginRequest request) => Ok();
}
// Minimal APIs
app.MapGet("/export", () => Results.Ok()).WithMetadata(new SkipResponseLoggingAttribute());
Best practices
- Skip request bodies on endpoints that receive passwords, tokens or other PII.
- Add health check and metrics paths to
IgnorePaths; they are high-frequency and low-value. - If you call
UseRouting()explicitly, add the middleware after it, so endpoint metadata (and the skip attributes) is available.