From 84a18f8619367ddb96554d37f7dc14cc1c1c5a50 Mon Sep 17 00:00:00 2001 From: a <a@tuxpa.in> Date: Wed, 28 Dec 2022 06:27:39 -0600 Subject: [PATCH] better middleware --- middleware/log.go | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/middleware/log.go b/middleware/log.go index 48f443a..7995ac4 100644 --- a/middleware/log.go +++ b/middleware/log.go @@ -1,24 +1,41 @@ package middleware -// Ported from Goji's middleware, source: -// jrpcs://github.com/zenazn/goji/tree/master/web/middleware - import ( + "context" "time" "gfx.cafe/open/jrpc" + "tuxpa.in/a/zlog" "tuxpa.in/a/zlog/log" ) +// Key to use when setting the request ID. +type ctxKeyLogger int + +// RequestIDKey is the key that holds the unique request ID in a request context. +const LoggerKey ctxKeyLogger = 76 + func Logger(next jrpc.Handler) jrpc.Handler { fn := func(w jrpc.ResponseWriter, r *jrpc.Request) { start := time.Now() - next.ServeRPC(w, r) - log.Trace(). - Stringer("time", time.Since(start)). + l := log.Trace(). + Str("id", GetReqID(r.Context())). Str("remote", r.Remote()). Str("method", r.Method). - Str("params", string(r.Msg().Params)).Msg("RPC Request") + Str("params", string(r.Msg().Params)) + next.ServeRPC(w, r.WithContext(context.WithValue(r.Context(), LoggerKey, l))) + l = l.Stringer("dur", time.Since(start)) + l.Msg("RPC Request") } return jrpc.HandlerFunc(fn) } + +func GetLogger(ctx context.Context) *zlog.Event { + if ctx == nil { + return log.Debug() + } + if lgr, ok := ctx.Value(LoggerKey).(*zlog.Event); ok { + return lgr + } + return log.Debug() +} -- GitLab