Skip to Content

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

FieldTypeDescription
Currently no configurable options-Pass nil or &middlewares.MiddlewareOptions{}

Log Fields

The middleware automatically logs the following fields for each request:

FieldTypeDescription
methodstringHTTP method (GET, POST, etc.)
pathstringRequest path (/api/users)
remote_addrstringClient IP address
status_codeintHTTP response status code
duration_msint64Request 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