This Web API project demonstrates how to capture and log every HTTP request and response using CSharpEssentials.RequestResponseLogging.
| Feature | File | Description |
|---|---|---|
| Request/Response Logging | Program.cs |
Captures full HTTP cycle including body, headers, and timing |
| Custom Log Writer | Infrastructure/StructuredJsonLogWriter.cs |
Formats logs as structured JSON with sensitive data masking |
| Path Filtering | Program.cs |
Excludes health check endpoints from logging |
| Body Truncation | StructuredJsonLogWriter.cs |
Prevents memory issues with large payloads |
| Sensitive Header Masking | StructuredJsonLogWriter.cs |
Masks Authorization, Cookie, X-Api-Key |
cd examples/Examples.RequestResponseLogging
dotnet runThe API will start on https://localhost:5001.
Use curl or any HTTP client to test the endpoints and observe the log output in the console.
curl -s https://localhost:5001/api/demo/hellocurl -s -X POST https://localhost:5001/api/demo/echo \
-H "Content-Type: application/json" \
-d '{"message":"Hello","repeatCount":3}'curl -s https://localhost:5001/api/demo/errorcurl -s -X POST https://localhost:5001/api/demo/validation \
-H "Content-Type: application/json" \
-d '{"name":"","age":10}'curl -s https://localhost:5001/api/demo/slowcurl -s https://localhost:5001/health{
"timestamp": "2025-01-15T10:30:45.123Z",
"traceId": "0HMP3...",
"durationMs": 12.45,
"request": {
"method": "POST",
"path": "/api/demo/echo",
"queryString": "",
"headers": {
"content-type": "application/json",
"authorization": "Bear****1234"
},
"body": "{\"message\":\"Hello\",\"repeatCount\":3}"
},
"response": {
"statusCode": 200,
"headers": { "content-type": "application/json; charset=utf-8" },
"body": "{\"received\":{...},\"serverTime\":\"2025-01-15T10:30:45.135Z\"}"
}
}app.AddRequestResponseLogging(opt =>
{
opt.IgnorePaths("/health", "/metrics");
opt.UseLogger(loggerFactory, options =>
{
options.LoggingLevel = LogLevel.Information;
});
});ILogWriter interface'i internal'dır — custom implementasyon için UseHandler(Func<RequestResponseContext, Task> handler) kullan.
- Sensitive Data Masking: Always mask
Authorization,Cookie, and API key headers. - Body Size Limits: Set
MaxBodyLengthto prevent out-of-memory errors with file uploads. - Path Filtering: Exclude health checks, metrics, and static file endpoints.
- PII Scrubbing: Extend the log writer to scan request/response bodies for PII.