Logger Middleware
The logger middleware automatically logs HTTP requests with structured logging. It captures request details, response
status codes, and processing duration using the clog
logging system. See logger for more details on how to use it.
Features
- Structured Logging: Uses
clog
for consistent, structured log output - Request Context: Integrates with the request context for logging consistency
- Response Capture: Captures HTTP status codes from responses
- Duration Tracking: Measures and logs request processing time
- Non-Blocking: Logs after the request is processed, not affecting performance
Basic Usage
middleware.go
httpx.Chain(
middlewares.Logger(nil),
)
Configuration
MiddlewareOptions Fields
Field | Type | Description |
---|---|---|
Currently no configurable options | - | Pass nil or &middlewares.MiddlewareOptions{} |
Log Fields
The middleware automatically logs the following fields for each request:
Field | Type | Description |
---|---|---|
method | string | HTTP method (GET, POST, etc.) |
path | string | Request path (/api/users ) |
remote_addr | string | Client IP address |
status_code | int | HTTP response status code |
duration_ms | int64 | Request processing time in milliseconds |
Enabled by Default
The logger middleware is enabled by default in the HTTP server configuration at (internal/provide/provide_http.go
):
Example Log Output
{
"level": "info",
"msg": "http request",
"method": "GET",
"path": "/api/users",
"remote_addr": "192.168.1.100",
"status_code": 200,
"duration_ms": 45,
"timestamp": "2025-01-15T10:30:00Z"
}
Add context to the logger in your handlers
You can add additional context to the logger in your handlers by using the clog
package. This allows you to enrich your logs with more information relevant to the request.
handler.go
func (h *UserHandler) Me() http.HandlerFunc {
return httpx.Chain(
requireUser(h.userSvc),
)(func(r *http.Request) (httpx.Response, error) {
var req MeRequest
if err := params.Bind(&req, r); err != nil {
return nil, err
}
clog.Add(r.Context(), "user_id", req.User.ID) // here :)
return httpx.JSON.Ok(MeResponse{
ID: req.User.ID,
Email: req.User.Email,
}), nil
})
}
Last updated on