package chizap import ( "net/http" "time" "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. // // 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...) 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", r.RemoteAddr), 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("time", end.Format(cfg.timeFormat)), } for _, fn := range cfg.additionalFieldExtractors { fields = append(fields, fn(r)...) } if statusCode >= http.StatusInternalServerError { logger.Error(path, fields...) } else if statusCode >= http.StatusBadRequest { logger.Warn(path, fields...) } else { logger.Info(path, fields...) } }) } }