package server import ( "log/slog" "net/http" "time" ) type statusRecorder struct { http.ResponseWriter status int } func (r *statusRecorder) WriteHeader(code int) { r.ResponseWriter.WriteHeader(code) r.status = code } func logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(recorder, r) attrs := []slog.Attr{ slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.Int("status", recorder.status), slog.Duration("duration", time.Since(start)), slog.String("remote", r.RemoteAddr), } if xff := r.Header.Get("x-forwarded-for"); xff != "" { attrs = append(attrs, slog.String("x-forwarded-for", xff)) } slog.LogAttrs(r.Context(), slog.LevelInfo, "request", attrs...) }) }