Skip to content

Commit

Permalink
SugaredLogger: Add WithOptions (#1079)
Browse files Browse the repository at this point in the history
Add a WithOptions method to SugaredLogger that allows specifying
building a copy of the logger with the specified options applied.

This allows turning,

    slog.Desugar().WithOptions(...).Sugar()

Into,

    slog.WithOptions(...)

Closes #1072
  • Loading branch information
Craig Pastro committed Apr 8, 2022
1 parent 212dcb9 commit 1d435ba
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
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

0 comments on commit 1d435ba

Please sign in to comment.