From 3704bb22317fe53e543bfb5cde30052213b1fb9d Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Sat, 12 Aug 2023 23:44:21 -0400 Subject: [PATCH] Better logging --- app/router.go | 3 ++- cmd/root.go | 2 +- pkg/middlewarex/slog.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 pkg/middlewarex/slog.go diff --git a/app/router.go b/app/router.go index 91109ff..75c1807 100644 --- a/app/router.go +++ b/app/router.go @@ -10,6 +10,7 @@ import ( "github.com/samber/lo" "github.com/spf13/viper" "go.fifitido.net/ytdl-web/pkg/httpx" + "go.fifitido.net/ytdl-web/pkg/middlewarex" "go.fifitido.net/ytdl-web/pkg/view" "go.fifitido.net/ytdl-web/version" "go.fifitido.net/ytdl-web/ytdl" @@ -22,7 +23,7 @@ func Router(ytdl ytdl.Ytdl) http.Handler { r.Use(middleware.RequestID) r.Use(middleware.RealIP) - r.Use(middleware.Logger) + r.Use(middlewarex.SlogRequestLogger(slog.Default().With("module", "app"))) r.Use(middleware.Recoverer) r.Get("/", indexHandler(ytdl)) diff --git a/cmd/root.go b/cmd/root.go index e5850d6..15c9161 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -85,7 +85,7 @@ func initLogging() { if cfg.IsProduction() { handler = slog.HandlerOptions{ AddSource: true, - Level: slog.LevelWarn, + Level: slog.LevelInfo, }.NewJSONHandler(os.Stdout) } else { handler = slog.HandlerOptions{ diff --git a/pkg/middlewarex/slog.go b/pkg/middlewarex/slog.go new file mode 100644 index 0000000..795c79e --- /dev/null +++ b/pkg/middlewarex/slog.go @@ -0,0 +1,37 @@ +package middlewarex + +import ( + "net/http" + "time" + + "github.com/go-chi/chi/v5/middleware" + "golang.org/x/exp/slog" +) + +func SlogRequestLogger(logger *slog.Logger) func(next http.Handler) http.Handler { + if logger == nil { + return func(next http.Handler) http.Handler { return next } + } + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + ti := time.Now() + + defer func() { + reqLogger := logger.With( + slog.String("proto", r.Proto), + slog.String("path", r.URL.Path), + slog.String("reqId", middleware.GetReqID(r.Context())), + slog.Duration("lat", time.Since(ti)), + slog.Int("status", ww.Status()), + slog.Int("size", ww.BytesWritten()), + ) + + reqLogger.Info("Served") + }() + + next.ServeHTTP(ww, r) + }) + } +}