diff --git a/logger.go b/logger.go index b5f9a99fd..cd44030d1 100644 --- a/logger.go +++ b/logger.go @@ -183,6 +183,13 @@ func (log *Logger) With(fields ...Field) *Logger { return l } +// Level reports the minimum enabled level for this logger. +// +// For NopLoggers, this is [zapcore.InvalidLevel]. +func (log *Logger) Level() zapcore.Level { + return zapcore.LevelOf(log.core) +} + // Check returns a CheckedEntry if logging a message at the specified level // is enabled. It's a completely optional optimization; in high-performance // applications, Check can help avoid allocating a slice to hold fields. diff --git a/logger_test.go b/logger_test.go index 063d5dd16..fffd653c1 100644 --- a/logger_test.go +++ b/logger_test.go @@ -83,6 +83,33 @@ func TestLoggerAtomicLevel(t *testing.T) { }) } +func TestLoggerLevel(t *testing.T) { + levels := []zapcore.Level{ + DebugLevel, + InfoLevel, + WarnLevel, + ErrorLevel, + DPanicLevel, + PanicLevel, + FatalLevel, + } + + for _, lvl := range levels { + lvl := lvl + t.Run(lvl.String(), func(t *testing.T) { + t.Parallel() + + core, _ := observer.New(lvl) + log := New(core) + assert.Equal(t, lvl, log.Level()) + }) + } + + t.Run("Nop", func(t *testing.T) { + assert.Equal(t, zapcore.InvalidLevel, NewNop().Level()) + }) +} + func TestLoggerInitialFields(t *testing.T) { fieldOpts := opts(Fields(Int("foo", 42), String("bar", "baz"))) withLogger(t, DebugLevel, fieldOpts, func(logger *Logger, logs *observer.ObservedLogs) { diff --git a/sugar.go b/sugar.go index c450b2dda..e42b694ed 100644 --- a/sugar.go +++ b/sugar.go @@ -114,6 +114,13 @@ func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger { return &SugaredLogger{base: s.base.With(s.sweetenFields(args)...)} } +// Level reports the minimum enabled level for this logger. +// +// For NopLoggers, this is [zapcore.InvalidLevel]. +func (s *SugaredLogger) Level() zapcore.Level { + return zapcore.LevelOf(s.base.core) +} + // Debug uses fmt.Sprint to construct and log a message. func (s *SugaredLogger) Debug(args ...interface{}) { s.log(DebugLevel, "", args, nil) diff --git a/sugar_test.go b/sugar_test.go index 1824e348f..9c067cbab 100644 --- a/sugar_test.go +++ b/sugar_test.go @@ -139,6 +139,35 @@ func TestSugarWith(t *testing.T) { } } +func TestSugaredLoggerLevel(t *testing.T) { + levels := []zapcore.Level{ + DebugLevel, + InfoLevel, + WarnLevel, + ErrorLevel, + DPanicLevel, + PanicLevel, + FatalLevel, + } + + for _, lvl := range levels { + lvl := lvl + t.Run(lvl.String(), func(t *testing.T) { + t.Parallel() + + core, _ := observer.New(lvl) + log := New(core).Sugar() + assert.Equal(t, lvl, log.Level()) + }) + } + + t.Run("Nop", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, zapcore.InvalidLevel, NewNop().Sugar().Level()) + }) +} + func TestSugarFieldsInvalidPairs(t *testing.T) { withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) { logger.With(42, "foo", []string{"bar"}, "baz").Info("")