Initial commit: unified dashboard suite state with Khira and Image Manipulator 3-file setup
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
// RequestLogger is a middleware that logs each request using slog
|
||||
func RequestLogger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
start := time.Now()
|
||||
|
||||
defer func() {
|
||||
status := ww.Status()
|
||||
duration := time.Since(start).Milliseconds()
|
||||
reqID := middleware.GetReqID(r.Context())
|
||||
|
||||
attrs := []any{
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration_ms", duration,
|
||||
"bytes", ww.BytesWritten(),
|
||||
"remote_addr", r.RemoteAddr,
|
||||
}
|
||||
if reqID != "" {
|
||||
attrs = append(attrs, "request_id", reqID)
|
||||
}
|
||||
|
||||
if status >= 500 {
|
||||
slog.Error("http request error", attrs...)
|
||||
} else if status >= 400 {
|
||||
slog.Warn("http request warning", attrs...)
|
||||
} else {
|
||||
slog.Info("http request", attrs...)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(ww, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user