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

zapcore: Add ParseLevel #1047

Merged
merged 5 commits into from Jan 13, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions zapcore/level.go
Expand Up @@ -55,6 +55,18 @@ const (
_maxLevel = FatalLevel
)

// ParseLevel parses a level based on the lower-case 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 ParseLevel(text string) (Level, error) {
var level Level
err := level.UnmarshalText([]byte(text))
return level, err
}

// String returns a lower-case ASCII representation of the log level.
func (l Level) String() string {
switch l {
Expand Down
22 changes: 22 additions & 0 deletions zapcore/level_test.go
Expand Up @@ -76,6 +76,28 @@ func TestLevelText(t *testing.T) {
}
}

func TestParseLevel(t *testing.T) {
tests := []struct {
text string
level Level
err string
}{
{"info", InfoLevel, ""},
{"DEBUG", DebugLevel, ""},
{"FOO", 0, `unrecognized level: "FOO"`},
}
for _, tt := range tests {
parsedLevel, err := ParseLevel(tt.text)
if len(tt.err) == 0 {
assert.NoError(t, err)
assert.Equal(t, tt.level, parsedLevel)
} else {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.err)
}
}
}

func TestCapitalLevelsParse(t *testing.T) {
tests := []struct {
text string
Expand Down