Skip to content

Commit

Permalink
fix(leak): Avoid mutating logger (#97)
Browse files Browse the repository at this point in the history
* Avoid mutating logger

* Change test to cover this scenario

* better comment

* lint
  • Loading branch information
pablomatiasgomez authored Nov 22, 2024
1 parent ee07bd7 commit 2406f68
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 4 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,16 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
}
}

// Use a separate logger to save to the context, as we want to avoid mutating the original logger.
contextLogger := rl
if track {
l = l.With().
contextLogger = rl.With().
Str("method", c.Request.Method).
Str("path", path).
Str("ip", c.ClientIP()).
Str("user_agent", c.Request.UserAgent()).Logger()
}
c.Set(loggerKey, l)
c.Set(loggerKey, contextLogger)

c.Next()

Expand Down
5 changes: 3 additions & 2 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,10 @@ func TestCustomLoggerIssue68(t *testing.T) {
buffer := new(concurrentBuffer)
gin.SetMode(gin.ReleaseMode)
r := gin.New()
l := zerolog.New(buffer)
// Use JSON logger as it will explicitly print keys multiple times if they are added multiple times,
// which may happen if there are mutations to the logger.
r.Use(SetLogger(
WithLogger(func(*gin.Context, zerolog.Logger) zerolog.Logger { return l }),
WithLogger(func(_ *gin.Context, l zerolog.Logger) zerolog.Logger { return l.Output(buffer).With().Logger() }),
WithDefaultLevel(zerolog.DebugLevel),
WithClientErrorLevel(zerolog.ErrorLevel),
WithServerErrorLevel(zerolog.FatalLevel),
Expand Down

0 comments on commit 2406f68

Please sign in to comment.