Guides
HTTP request logging
Log requests with standard HTTP middleware and configure levels, request IDs, and skip rules.
Wrap an HTTP handler
Wrap a standard-library http.Handler with HTTPMiddleware. It logs each request once after handling it unless a skip rule matches. The zero value of HTTPConfig works and records fields such as method, path, and response status.
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stable}))
handler := sl.HTTPMiddleware(logger, sl.HTTPConfig{})(http.NotFoundHandler())
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/missing", nil))level=WARN msg="http request" request.method=GET request.path=/missing request.query="" request.ip=192.0.2.1:1234 request.user_agent="" response.status=404 response.bytes=19Customize logging by request
The example uses HTTPConfig.RequestIDHeader to record a chosen request header and HTTPConfig.Skip to skip health checks. It maps 404 to Debug and delegates other status codes to StatusLevel. By default, 2xx and 3xx log at Info, 4xx at Warn, and 5xx at Error.
// The zero HTTPConfig works as is. This one also logs the request ID,
// logs 404s at Debug, and skips the health check.
handler := sl.HTTPMiddleware(logger, sl.HTTPConfig{
RequestIDHeader: "X-Request-Id",
Level: func(status int) slog.Level {
if status == http.StatusNotFound {
return slog.LevelDebug
}
return sl.StatusLevel(status) // the default: 2xx/3xx Info, 4xx Warn, 5xx Error
},
Skip: func(r *http.Request) bool { return r.URL.Path == "/healthz" },
})(mux)
// In a real server: http.ListenAndServe(":8080", handler)