From 1d435ba52bfab52b187ef66596203ddcf65e51cb Mon Sep 17 00:00:00 2001 From: Craig Pastro Date: Fri, 8 Apr 2022 10:16:09 -0700 Subject: [PATCH] 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 --- sugar.go | 10 ++++++++++ sugar_test.go | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/sugar.go b/sugar.go index 0b9651981..4f9d491a0 100644 --- a/sugar.go +++ b/sugar.go @@ -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 diff --git a/sugar_test.go b/sugar_test.go index 411759ad8..8cb0f9443 100644 --- a/sugar_test.go +++ b/sugar_test.go @@ -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++ {