Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zap: Add ParseAtomicLevel func #1048

Merged
merged 2 commits into from Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

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

// ParseAtomicLevel parses a level based on the lower-case or all-caps ASCII
Techassi marked this conversation as resolved.
Show resolved Hide resolved
// 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
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