Skip to content

Commit 3aad289

Browse files
authored
Merge pull request #2 from trinhdaiphuc/feature/change-set-context-key
change set context key gin
2 parents 7e79bdf + 6336be2 commit 3aad289

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

gin.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func GinMiddleware() gin.HandlerFunc {
2727
UserAgentField: userAgent,
2828
URIField: uri,
2929
})
30-
ctx.Request = ctx.Request.WithContext(context.WithValue(ctx, Key, logger))
30+
ctx.Request = ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), Key, logger))
3131
ctx.Set(Key, logger)
3232
ctx.Next()
3333
var (

logger.go

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,23 @@ func WithOutput(output io.Writer) Option {
6060

6161
// GetLogger get logger from context
6262
func GetLogger(ctx context.Context) *Log {
63-
logger, ok := ctx.Value(Key).(*Log)
64-
if !ok {
65-
logger := New()
66-
ctx = context.WithValue(
67-
ctx,
68-
Key, logger)
69-
return logger
63+
loggerCtx := ctx.Value(Key)
64+
if loggerCtx == nil {
65+
goto NewLogger
66+
} else {
67+
logger, ok := loggerCtx.(*Log)
68+
if !ok {
69+
goto NewLogger
70+
} else {
71+
return logger
72+
}
7073
}
71-
return logger
74+
NewLogger:
75+
newLogger := New()
76+
ctx = context.WithValue(
77+
ctx,
78+
Key, newLogger)
79+
return newLogger
7280
}
7381

7482
// ToJsonString convert an object into json string to beautify log

0 commit comments

Comments
 (0)