chizap/logger.go

65 lines
1.7 KiB
Go
Raw Normal View History

2021-08-31 06:03:13 +00:00
package chizap
import (
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)
2021-08-31 06:03:13 +00:00
// Logger returns a go-chi middleware that logs requests using go.uber.org/zap.
//
// Requests with status code >= 500 are logged using logger.Error.
// Requests with status code >= 400 are logged using logger.Warn.
// Other requests are logged using logger.Info.
func Logger(logger *zap.Logger, opts ...Option) func(next http.Handler) http.Handler {
cfg := newConfig(opts...)
2021-08-31 06:03:13 +00:00
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
}
2021-08-31 06:03:13 +00:00
}
path := r.URL.Path
query := r.URL.RawQuery
2021-08-31 06:03:13 +00:00
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
start := time.Now()
2021-11-30 10:23:21 +00:00
2021-08-31 06:03:13 +00:00
next.ServeHTTP(ww, r)
2021-11-30 10:23:21 +00:00
end := time.Now()
2021-08-31 06:03:13 +00:00
statusCode := ww.Status()
fields := []zap.Field{
zap.Int("statusCode", statusCode),
zap.Duration("duration", end.Sub(start)),
zap.String("ip", r.RemoteAddr),
2021-08-31 06:03:13 +00:00
zap.String("method", r.Method),
zap.String("query", query),
2021-08-31 06:03:13 +00:00
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("time", end.Format(cfg.timeFormat)),
}
for _, fn := range cfg.additionalFieldExtractors {
fields = append(fields, fn(r)...)
2021-08-31 06:03:13 +00:00
}
if statusCode >= http.StatusInternalServerError {
logger.Error(path, fields...)
2021-08-31 06:03:13 +00:00
} else if statusCode >= http.StatusBadRequest {
logger.Warn(path, fields...)
2021-08-31 06:03:13 +00:00
} else {
logger.Info(path, fields...)
2021-08-31 06:03:13 +00:00
}
})
}
}