28 lines
829 B
Go
28 lines
829 B
Go
|
|
package mw
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||
|
|
)
|
||
|
|
|
||
|
|
// RequestLogger logs each request after the handler returns, including method,
|
||
|
|
// path, status code, and latency. Uses [StatusRecorder] to capture the status.
|
||
|
|
// Place after [RequestID] so the request ID is available in the log record.
|
||
|
|
func RequestLogger(logger logging.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()
|
||
|
|
rec := &StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
||
|
|
next.ServeHTTP(rec, r)
|
||
|
|
logger.WithContext(r.Context()).Info("request",
|
||
|
|
"method", r.Method,
|
||
|
|
"path", r.URL.Path,
|
||
|
|
"status", rec.Status,
|
||
|
|
"latency", time.Since(start).String(),
|
||
|
|
)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|