From ee761d400612e2b6733c7af35e6a81fd08ad0941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Mon, 24 Jan 2022 22:53:46 +0100 Subject: [PATCH] Change access logger --- api/middleware.go | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/api/middleware.go b/api/middleware.go index de94064..7d57ab3 100644 --- a/api/middleware.go +++ b/api/middleware.go @@ -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)