Skip to content

Commit 2406f68

Browse files
fix(leak): Avoid mutating logger (#97)
* Avoid mutating logger * Change test to cover this scenario * better comment * lint
1 parent ee07bd7 commit 2406f68

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

logger.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,14 +137,16 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
137137
}
138138
}
139139

140+
// Use a separate logger to save to the context, as we want to avoid mutating the original logger.
141+
contextLogger := rl
140142
if track {
141-
l = l.With().
143+
contextLogger = rl.With().
142144
Str("method", c.Request.Method).
143145
Str("path", path).
144146
Str("ip", c.ClientIP()).
145147
Str("user_agent", c.Request.UserAgent()).Logger()
146148
}
147-
c.Set(loggerKey, l)
149+
c.Set(loggerKey, contextLogger)
148150

149151
c.Next()
150152

logger_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,10 @@ func TestCustomLoggerIssue68(t *testing.T) {
180180
buffer := new(concurrentBuffer)
181181
gin.SetMode(gin.ReleaseMode)
182182
r := gin.New()
183-
l := zerolog.New(buffer)
183+
// Use JSON logger as it will explicitly print keys multiple times if they are added multiple times,
184+
// which may happen if there are mutations to the logger.
184185
r.Use(SetLogger(
185-
WithLogger(func(*gin.Context, zerolog.Logger) zerolog.Logger { return l }),
186+
WithLogger(func(_ *gin.Context, l zerolog.Logger) zerolog.Logger { return l.Output(buffer).With().Logger() }),
186187
WithDefaultLevel(zerolog.DebugLevel),
187188
WithClientErrorLevel(zerolog.ErrorLevel),
188189
WithServerErrorLevel(zerolog.FatalLevel),

0 commit comments

Comments
 (0)