Skip to content

Commit

Permalink
zap: Add ParseAtomicLevel func (#1048)
Browse files Browse the repository at this point in the history
As discussed in #1047 this PR adds a zap.ParseAtomicLevel() func which enables the user to construct a log level based on ASCII text input.

Usage
```
level, err := zap.ParseAtomicLevel("info") // InfoLevel, nil
level, err := zap.ParseAtomicLevel("DEBUG") // DebugLevel, nil
level, err := zap.ParseAtomicLevel("FOO") // InfoLevel, "unrecognized level: "FOO""
```

Co-authored-by: Sung Yoon Whang <sungyoonwhang@gmail.com>

Co-authored-by: Sung Yoon Whang <sungyoonwhang@gmail.com>
  • Loading branch information
Techassi and sywhang authored Jan 14, 2022
1 parent e751939 commit c087e07
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
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

0 comments on commit c087e07

Please sign in to comment.