Skip to content

Commit

Permalink
add Level Off
Browse files Browse the repository at this point in the history
Add an Off log level so that loggers can be easily disabled while
allowing other named loggers to use the same synchronized output.
  • Loading branch information
jbardin committed Oct 22, 2020
1 parent 6b37787 commit 7379eb4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ const (

// Error information about unrecoverable events.
Error Level = 5

// Off disables all logging output.
Off Level = 6
)

// Format is a simple convience type for when formatting is required. When
Expand Down Expand Up @@ -96,6 +99,8 @@ func LevelFromString(levelStr string) Level {
return Warn
case "error":
return Error
case "off":
return Off
default:
return NoLevel
}
Expand All @@ -115,6 +120,8 @@ func (l Level) String() string {
return "error"
case NoLevel:
return "none"
case Off:
return "off"
default:
return "unknown"
}
Expand Down
26 changes: 26 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,32 @@ func TestLogger(t *testing.T) {
rest = str[dataIdx+1:]
assert.Equal(t, "[INFO] this is another test: production=\"13 beans/day\"\n", rest)
})

t.Run("named logger with disabled parent", func(t *testing.T) {
var buf bytes.Buffer

logger := New(&LoggerOptions{
// No name!
Output: &buf,
Level: Off,
})

logger.Info("this is test")
str := buf.String()
if len(str) > 0 {
t.Fatal("output from disabled logger:", str)
}

buf.Reset()

another := logger.Named("sublogger")
another.SetLevel(Info)
another.Info("this is test")
str = buf.String()
dataIdx := strings.IndexByte(str, ' ')
rest := str[dataIdx+1:]
assert.Equal(t, "[INFO] sublogger: this is test\n", rest)
})
}

func TestLogger_leveledWriter(t *testing.T) {
Expand Down

0 comments on commit 7379eb4

Please sign in to comment.