Skip to content

Commit

Permalink
Merge pull request #2 from trinhdaiphuc/feature/change-set-context-key
Browse files Browse the repository at this point in the history
change set context key gin
  • Loading branch information
trinhdaiphuc authored Jun 9, 2022
2 parents 7e79bdf + 6336be2 commit 3aad289
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
2 changes: 1 addition & 1 deletion gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
24 changes: 16 additions & 8 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 3aad289

Please sign in to comment.