You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package chizap
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// Logger returns a go-chi middleware that logs requests using go.uber.org/zap.
|
|
func Logger(logger *zap.Logger, opts ...Option) func(next http.Handler) http.Handler {
|
|
cfg := newConfig(opts...)
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
for _, f := range cfg.filters {
|
|
if !f(r) {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
}
|
|
|
|
path := r.URL.Path
|
|
query := r.URL.RawQuery
|
|
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
start := time.Now()
|
|
|
|
next.ServeHTTP(ww, r)
|
|
|
|
end := time.Now()
|
|
statusCode := ww.Status()
|
|
|
|
fields := []zap.Field{
|
|
zap.Int("statusCode", statusCode),
|
|
zap.Duration("duration", end.Sub(start)),
|
|
zap.String("ip", cfg.ipFn(r)),
|
|
zap.String("method", r.Method),
|
|
zap.String("query", query),
|
|
zap.String("path", path),
|
|
zap.String("proto", r.Proto),
|
|
zap.String("referer", r.Referer()),
|
|
zap.Int("contentSize", ww.BytesWritten()),
|
|
zap.String("userAgent", r.UserAgent()),
|
|
zap.String("routePattern", chi.RouteContext(r.Context()).RoutePattern()),
|
|
}
|
|
|
|
for _, f := range cfg.additionalFieldExtractors {
|
|
fields = append(fields, f(r)...)
|
|
}
|
|
|
|
if statusCode >= http.StatusInternalServerError {
|
|
logger.Error(path, fields...)
|
|
} else if statusCode >= http.StatusBadRequest {
|
|
logger.Warn(path, fields...)
|
|
} else {
|
|
logger.Info(path, fields...)
|
|
}
|
|
})
|
|
}
|
|
}
|