Better logging
This commit is contained in:
parent
d7e5ccc332
commit
3704bb2231
|
@ -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))
|
||||
|
|
|
@ -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{
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue