Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(leak): Avoid mutating logger #97

Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
4 changes: 2 additions & 2 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ 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 (if there were 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() }),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason why this was not caught by this test is because the modifications to the logger basically add method, path, ip, and user_agent which are ALSO added to the event, but without json it seems to dedupe these keys.

WithDefaultLevel(zerolog.DebugLevel),
WithClientErrorLevel(zerolog.ErrorLevel),
WithServerErrorLevel(zerolog.FatalLevel),
Expand Down
Loading