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

Add WithOptions to SugaredLogger #1079

Merged
merged 3 commits into from Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions sugar.go
Expand Up @@ -61,6 +61,16 @@ func (s *SugaredLogger) Named(name string) *SugaredLogger {
return &SugaredLogger{base: s.base.Named(name)}
}

// WithOptions clones the current SugaredLogger, applies the supplied Options,
// and returns the result. It's safe to use concurrently.
func (s *SugaredLogger) WithOptions(opts ...Option) *SugaredLogger {
base := s.base.clone()
for _, opt := range opts {
opt.apply(base)
}
return &SugaredLogger{base: base}
}

// With adds a variadic number of fields to the logging context. It accepts a
// mix of strongly-typed Field objects and loosely-typed key-value pairs. When
// processing pairs, the first element of the pair is used as the field key
Expand Down
16 changes: 16 additions & 0 deletions sugar_test.go
Expand Up @@ -369,6 +369,22 @@ func TestSugarAddCallerFail(t *testing.T) {
})
}

func TestSugarWithOptionsIncreaseLevel(t *testing.T) {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger = logger.WithOptions(IncreaseLevel(WarnLevel))
logger.Info("logger.Info")
logger.Warn("logger.Warn")
logger.Error("logger.Error")
require.Equal(t, 2, logs.Len(), "expected only warn + error logs due to IncreaseLevel.")
assert.Equal(
t,
logs.AllUntimed()[0].Message,
"logger.Warn",
"Expected first logged message to be warn level message",
)
})
}

func BenchmarkSugarSingleStrArg(b *testing.B) {
withSugar(b, InfoLevel, nil /* opts* */, func(log *SugaredLogger, logs *observer.ObservedLogs) {
for i := 0; i < b.N; i++ {
Expand Down