Files
2026-06-10 14:48:28 +08:00

35 lines
1.1 KiB
Go

package middleware
import (
"log/slog"
"net/http"
"time"
"github.com/felixge/httpsnoop"
)
// Logger returns HTTP middleware that emits a single structured log line
// per request once the downstream handler has finished. The line includes
// method, path, response status, elapsed duration in milliseconds, and the
// request ID (if RequestID middleware is mounted upstream).
//
// The middleware is intentionally placed *inside* RequestID so the
// generated identifier is available via context; placing it outside would
// log an empty request_id.
func Logger(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
metrics := httpsnoop.CaptureMetrics(next, w, r)
ctx := r.Context()
log.LogAttrs(ctx, slog.LevelInfo, "http",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", metrics.Code),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
slog.String("request_id", RequestIDFromContext(ctx)),
)
})
}
}