From 6336be217ae5816e308c5e56b8197404ab258519 Mon Sep 17 00:00:00 2001 From: trinhdaiphuc Date: Thu, 9 Jun 2022 17:24:43 +0700 Subject: [PATCH] change set context key gin --- gin.go | 2 +- logger.go | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/gin.go b/gin.go index 131bcf3..4279af9 100644 --- a/gin.go +++ b/gin.go @@ -27,7 +27,7 @@ func GinMiddleware() gin.HandlerFunc { UserAgentField: userAgent, URIField: uri, }) - ctx.Request = ctx.Request.WithContext(context.WithValue(ctx, Key, logger)) + ctx.Request = ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), Key, logger)) ctx.Set(Key, logger) ctx.Next() var ( diff --git a/logger.go b/logger.go index 3511997..dcdcad3 100644 --- a/logger.go +++ b/logger.go @@ -60,15 +60,23 @@ func WithOutput(output io.Writer) Option { // GetLogger get logger from context func GetLogger(ctx context.Context) *Log { - logger, ok := ctx.Value(Key).(*Log) - if !ok { - logger := New() - ctx = context.WithValue( - ctx, - Key, logger) - return logger + loggerCtx := ctx.Value(Key) + if loggerCtx == nil { + goto NewLogger + } else { + logger, ok := loggerCtx.(*Log) + if !ok { + goto NewLogger + } else { + return logger + } } - return logger +NewLogger: + newLogger := New() + ctx = context.WithValue( + ctx, + Key, newLogger) + return newLogger } // ToJsonString convert an object into json string to beautify log