Skip to content

Commit 1d435ba

Browse files
author
Craig Pastro
authored
SugaredLogger: Add WithOptions (#1079)
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
1 parent 212dcb9 commit 1d435ba

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

sugar.go

+10
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,16 @@ func (s *SugaredLogger) Named(name string) *SugaredLogger {
6161
return &SugaredLogger{base: s.base.Named(name)}
6262
}
6363

64+
// WithOptions clones the current SugaredLogger, applies the supplied Options,
65+
// and returns the result. It's safe to use concurrently.
66+
func (s *SugaredLogger) WithOptions(opts ...Option) *SugaredLogger {
67+
base := s.base.clone()
68+
for _, opt := range opts {
69+
opt.apply(base)
70+
}
71+
return &SugaredLogger{base: base}
72+
}
73+
6474
// With adds a variadic number of fields to the logging context. It accepts a
6575
// mix of strongly-typed Field objects and loosely-typed key-value pairs. When
6676
// processing pairs, the first element of the pair is used as the field key

sugar_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,22 @@ func TestSugarAddCallerFail(t *testing.T) {
369369
})
370370
}
371371

372+
func TestSugarWithOptionsIncreaseLevel(t *testing.T) {
373+
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
374+
logger = logger.WithOptions(IncreaseLevel(WarnLevel))
375+
logger.Info("logger.Info")
376+
logger.Warn("logger.Warn")
377+
logger.Error("logger.Error")
378+
require.Equal(t, 2, logs.Len(), "expected only warn + error logs due to IncreaseLevel.")
379+
assert.Equal(
380+
t,
381+
logs.AllUntimed()[0].Message,
382+
"logger.Warn",
383+
"Expected first logged message to be warn level message",
384+
)
385+
})
386+
}
387+
372388
func BenchmarkSugarSingleStrArg(b *testing.B) {
373389
withSugar(b, InfoLevel, nil /* opts* */, func(log *SugaredLogger, logs *observer.ObservedLogs) {
374390
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)