Change access logger
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Torjus Håkestad 2022-01-24 22:53:46 +01:00
parent 8ae5ee64bb
commit ee761d4006

View File

@ -10,6 +10,7 @@ import (
"git.t-juice.club/torjus/gpaste"
"git.t-juice.club/torjus/gpaste/users"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)
type authCtxKey int
@ -27,14 +28,38 @@ func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
reqID := middleware.GetReqID(r.Context())
// TODO: Maybe desugar in HTTPServer to avoid doing for all requests
logger := s.AccessLogger.Desugar()
defer func() {
s.AccessLogger.Infow(r.Method,
"path", r.URL.Path,
"status", ww.Status(),
"written", ww.BytesWritten(),
"remote_addr", r.RemoteAddr,
"processing_time_ms", time.Since(t1).Milliseconds(),
"req_id", reqID)
// DEBUG level
if ce := logger.Check(zap.DebugLevel, r.Method); ce != nil {
ct := r.Header.Get("Content-Type")
ce.Write(
zap.String("req_id", reqID),
zap.String("path", r.URL.Path),
zap.Int("status", ww.Status()),
zap.String("remote_addr", r.RemoteAddr),
zap.Int("bytes_written", ww.BytesWritten()),
zap.Duration("processing_time", time.Since(t1)),
zap.String("content_type", ct),
zap.Any("headers", r.Header),
)
} else {
// INFO level
if ce := logger.Check(zap.InfoLevel, r.Method); ce != nil {
ce.Write(
zap.String("req_id", reqID),
zap.String("path", r.URL.Path),
zap.Int("status", ww.Status()),
zap.String("remote_addr", r.RemoteAddr),
zap.Int("bytes_written", ww.BytesWritten()),
zap.Duration("processing_time", time.Since(t1)),
)
}
}
_ = logger.Sync()
}()
next.ServeHTTP(ww, r)