33 lines
887 B
Go
33 lines
887 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
chiMiddleware "github.com/go-chi/chi/v5/middleware"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// Logger returns a chi-compatible middleware that logs requests using zap.
|
|
func Logger(logger *zap.Logger) func(next http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
ww := chiMiddleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
next.ServeHTTP(ww, r)
|
|
|
|
logger.Info("request",
|
|
zap.String("method", r.Method),
|
|
zap.String("path", r.URL.Path),
|
|
zap.String("query", r.URL.RawQuery),
|
|
zap.Int("status", ww.Status()),
|
|
zap.Int("bytes", ww.BytesWritten()),
|
|
zap.Duration("duration", time.Since(start)),
|
|
zap.String("ip", r.RemoteAddr),
|
|
zap.String("request_id", chiMiddleware.GetReqID(r.Context())),
|
|
)
|
|
})
|
|
}
|
|
}
|