From 0225bc581d6a95cb94306ff115b027a73f70de04 Mon Sep 17 00:00:00 2001 From: a <a@tuxpa.in> Date: Tue, 29 Aug 2023 18:26:58 -0500 Subject: [PATCH] change log package --- contrib/middleware/log.go | 52 ++++++++++++++++++++++++--------------- go.mod | 2 +- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/contrib/middleware/log.go b/contrib/middleware/log.go index bd3fb8b..a14e265 100644 --- a/contrib/middleware/log.go +++ b/contrib/middleware/log.go @@ -2,11 +2,11 @@ package middleware import ( "context" - "gfx.cafe/open/jrpc/pkg/codec" "time" - "tuxpa.in/a/zlog" - "tuxpa.in/a/zlog/log" + "gfx.cafe/open/jrpc/pkg/codec" + + "log/slog" ) // Key to use when setting the request ID. @@ -15,29 +15,41 @@ type ctxKeyLogger int // RequestIDKey is the key that holds the unique request ID in a request context. const LoggerKey ctxKeyLogger = 76 -func Logger(next codec.Handler) codec.Handler { - fn := func(w codec.ResponseWriter, r *codec.Request) { - start := time.Now() - l := log.Trace(). - Str("remote", r.Remote()). - Str("method", r.Method). - Str("params", string(r.Msg().Params)) - next.ServeRPC(w, r.WithContext(context.WithValue(r.Context(), LoggerKey, l))) - if id := GetReqID(r.Context()); id != "" { - l = l.Str("id", id) +func NewLogger(logger *slog.Logger) func(next codec.Handler) codec.Handler { + return func(next codec.Handler) codec.Handler { + fn := func(w codec.ResponseWriter, r *codec.Request) { + start := time.Now() + lg := logger.With( + "remote", r.Remote(), + "method", r.Method, + "params", string(r.Msg().Params), + ) + if id := GetReqID(r.Context()); id != "" { + lg = logger.With( + "req_id", id, + ) + } + next.ServeRPC(w, r.WithContext(context.WithValue(r.Context(), LoggerKey, lg))) + lg = logger.With( + "params", time.Since(start), + ) + logger.LogAttrs(r.Context(), slog.LevelDebug, "RPC Request") } - l = l.Stringer("dur", time.Since(start)) - l.Msg("RPC Request") + return codec.HandlerFunc(fn) } - return codec.HandlerFunc(fn) } -func GetLogger(ctx context.Context) *zlog.Event { +func Logger(next codec.Handler) codec.Handler { + lh := slog.Default() + return NewLogger(lh)(next) +} + +func GetLogger(ctx context.Context) *slog.Logger { if ctx == nil { - return log.Debug() + return slog.Default() } - if lgr, ok := ctx.Value(LoggerKey).(*zlog.Event); ok { + if lgr, ok := ctx.Value(LoggerKey).(*slog.Logger); ok { return lgr } - return log.Debug() + return slog.Default() } diff --git a/go.mod b/go.mod index e914fcb..fb073c1 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module gfx.cafe/open/jrpc -go 1.18 +go 1.21 require ( gfx.cafe/open/websocket v1.9.2 -- GitLab