Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ func NewAtomicLevelAt(l zapcore.Level) AtomicLevel {
return a
}

// ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII
// representation of the log level. If the provided ASCII representation is
// invalid an error is returned.
//
// This is particularly useful when dealing with text input to configure log
// levels.
func ParseAtomicLevel(text string) (AtomicLevel, error) {
a := NewAtomicLevel()
l, err := zapcore.ParseLevel(text)
if err != nil {
return a, err
}

a.SetLevel(l)
return a, nil
}

// Enabled implements the zapcore.LevelEnabler interface, which allows the
// AtomicLevel to be used in place of traditional static levels.
func (lvl AtomicLevel) Enabled(l zapcore.Level) bool {
Expand Down
23 changes: 23 additions & 0 deletions level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,29 @@ func TestNewAtomicLevel(t *testing.T) {
assert.Equal(t, WarnLevel, lvl.Level(), "Unexpected level after SetLevel.")
}

func TestParseAtomicLevel(t *testing.T) {
tests := []struct {
text string
level AtomicLevel
err string
}{
{"info", NewAtomicLevel(), ""},
{"DEBUG", NewAtomicLevelAt(DebugLevel), ""},
{"FOO", NewAtomicLevel(), `unrecognized level: "FOO"`},
}

for _, tt := range tests {
parsedAtomicLevel, err := ParseAtomicLevel(tt.text)
if len(tt.err) == 0 {
assert.NoError(t, err)
assert.Equal(t, tt.level, parsedAtomicLevel)
} else {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.err)
}
}
}

func TestAtomicLevelMutation(t *testing.T) {
lvl := NewAtomicLevel()
lvl.SetLevel(WarnLevel)
Expand Down