Skip to content

Commit

Permalink
zapcore: Add ParseLevel (#1047)
Browse files Browse the repository at this point in the history
This adds the public ParseLevel function which enables the user to
construct a log level based on ASCII text input.

This re-uses the UnmarshalText method of Level for the heavy-lifting,
but it avoids the user having to declare a local `Level` variable first.


```go
var level zapcore.Level
err := level.UnmarshalText([]byte("debug"))

// versus
level, err := zapcore.ParseLevel("debug")
```

#### Usage

```go
level, err := zapcore.LevelFromString("info")
// zapcore.InfoLevel, nil

level, err := zapcore.LevelFromString("DEBUG")
// zapcore.DebugLevel, nil

level, err := zapcore.LevelFromString("FOO")
// 0, "invalid level"
```

Co-authored-by: Abhinav Gupta <[email protected]>
  • Loading branch information
Techassi and abhinav authored Jan 13, 2022
1 parent ad0b02d commit e751939
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions zapcore/level.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit e751939

Please sign in to comment.