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