Overview
Therequestlog middleware provides detailed structured logging of HTTP requests with configurable fields and formats.
Use it when you need:
- Structured request logs
- Detailed debugging info
- Log aggregation integration
Installation
Quick Start
Configuration
Options
Examples
Default Logging
With slog
Custom Fields
Skip Health Checks
Error Level for Errors
Log Output
API Reference
Functions
Technical Details
Implementation
The requestlog middleware is built on Go’slog/slog package and provides structured logging with the following key features:
- Timing: Uses
time.Now()andtime.Since()to measure request duration with nanosecond precision - Skip Logic: Pre-computes skip paths and methods into maps for O(1) lookup performance
- Body Preservation: Reads request body using
io.LimitReaderand restores it withio.NopCloser(bytes.NewReader(body))to allow downstream handlers to access it - Header Redaction: Maintains a map of sensitive header names for constant-time redaction checks
- Default Values: Automatically sets default logger (text handler to stdout), max body size (4KB), and sensitive headers (Authorization, Cookie, X-API-Key)
Logged Fields
The middleware logs the following fields for each request:method: HTTP method (GET, POST, etc.)path: Request URL pathremote_addr: Client remote addressquery: Raw query string (only if present)headers: Request headers (only ifLogHeaders: true)body: Request body up toMaxBodySize(only ifLogBody: true)duration: Request processing durationerror: Error message (only if request returns an error)
Error Handling
When a request handler returns an error:- The error is logged at ERROR level with all request attributes
- The error is propagated to the next middleware (not swallowed)
- Request duration is still calculated and logged
Security Considerations
Sensitive Data Protection
The middleware automatically redacts sensitive headers to prevent credential leakage:- Default sensitive headers:
Authorization,Cookie,X-API-Key - Custom sensitive headers can be configured via
SensitiveHeadersoption - Redacted headers show
[REDACTED]in logs
Body Logging Risks
WhenLogBody: true:
- Request bodies may contain passwords, tokens, or PII
- Body size is limited by
MaxBodySize(default 4KB) to prevent memory exhaustion - Consider using skip logic for authentication endpoints
- Review compliance requirements (GDPR, HIPAA, etc.) before enabling
Best Practices
- Use structured logging for aggregation
- Skip noisy endpoints
- Include request IDs for correlation
- Set appropriate log levels
- Be cautious with
LogBodyon production systems - Configure
SensitiveHeadersfor your application’s needs - Use
SkipPathsfor health checks and metrics endpoints - Set reasonable
MaxBodySizelimits to prevent memory issues