Skip to content

Commit c087e07

Browse files
Techassisywhang
andauthored
zap: Add ParseAtomicLevel func (#1048)
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 <[email protected]> Co-authored-by: Sung Yoon Whang <[email protected]>
1 parent e751939 commit c087e07

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

level.go

+17
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,23 @@ func NewAtomicLevelAt(l zapcore.Level) AtomicLevel {
8686
return a
8787
}
8888

89+
// ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII
90+
// representation of the log level. If the provided ASCII representation is
91+
// invalid an error is returned.
92+
//
93+
// This is particularly useful when dealing with text input to configure log
94+
// levels.
95+
func ParseAtomicLevel(text string) (AtomicLevel, error) {
96+
a := NewAtomicLevel()
97+
l, err := zapcore.ParseLevel(text)
98+
if err != nil {
99+
return a, err
100+
}
101+
102+
a.SetLevel(l)
103+
return a, nil
104+
}
105+
89106
// Enabled implements the zapcore.LevelEnabler interface, which allows the
90107
// AtomicLevel to be used in place of traditional static levels.
91108
func (lvl AtomicLevel) Enabled(l zapcore.Level) bool {

level_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,29 @@ func TestNewAtomicLevel(t *testing.T) {
5757
assert.Equal(t, WarnLevel, lvl.Level(), "Unexpected level after SetLevel.")
5858
}
5959

60+
func TestParseAtomicLevel(t *testing.T) {
61+
tests := []struct {
62+
text string
63+
level AtomicLevel
64+
err string
65+
}{
66+
{"info", NewAtomicLevel(), ""},
67+
{"DEBUG", NewAtomicLevelAt(DebugLevel), ""},
68+
{"FOO", NewAtomicLevel(), `unrecognized level: "FOO"`},
69+
}
70+
71+
for _, tt := range tests {
72+
parsedAtomicLevel, err := ParseAtomicLevel(tt.text)
73+
if len(tt.err) == 0 {
74+
assert.NoError(t, err)
75+
assert.Equal(t, tt.level, parsedAtomicLevel)
76+
} else {
77+
assert.Error(t, err)
78+
assert.Contains(t, err.Error(), tt.err)
79+
}
80+
}
81+
}
82+
6083
func TestAtomicLevelMutation(t *testing.T) {
6184
lvl := NewAtomicLevel()
6285
lvl.SetLevel(WarnLevel)

0 commit comments

Comments
 (0)