Skip to content

Commit 1214cf5

Browse files
add ParseLevel func to return level const
this will allow consumers of this package to not have to do their own logic to convert known log levels to the constants defined for each one within this package.
1 parent 6267eb7 commit 1214cf5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

log/log.go

+19
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"path"
1010
"runtime"
1111
"strconv"
12+
"strings"
1213
"sync"
1314
"sync/atomic"
1415
"time"
@@ -248,6 +249,24 @@ func Level() Lvl {
248249
return global.Level()
249250
}
250251

252+
func ParseLevel(lvl string) (Lvl, error) {
253+
switch strings.ToUpper(lvl) {
254+
case "DEBUG":
255+
return DEBUG, nil
256+
case "INFO":
257+
return INFO, nil
258+
case "WARN":
259+
return WARN, nil
260+
case "ERROR":
261+
return ERROR, nil
262+
case "OFF":
263+
return OFF, nil
264+
}
265+
266+
var l Lvl
267+
return l, fmt.Errorf("not a valid log level: '%s'", lvl)
268+
}
269+
251270
func SetLevel(level Lvl) {
252271
global.SetLevel(level)
253272
}

log/log_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package log
22

33
import (
44
"bytes"
5+
"errors"
56
"os"
67
"os/exec"
78
"sync"
@@ -75,6 +76,31 @@ func TestFatal(t *testing.T) {
7576
loggerFatalTest(t, "fatalf", "fatal-f")
7677
}
7778

79+
func TestParseLevel(t *testing.T) {
80+
testCases := map[string]struct {
81+
input string
82+
expectedLvl Lvl
83+
expectedErr error
84+
}{
85+
"DEBUG": {"DEBUG", DEBUG, nil},
86+
"INFO": {"INFO", INFO, nil},
87+
"WARN": {"WARN", WARN, nil},
88+
"ERROR": {"ERROR", ERROR, nil},
89+
"OFF": {"OFF", OFF, nil},
90+
"lowercase": {"debug", DEBUG, nil},
91+
"mixedcase": {"WaRn", WARN, nil},
92+
"unknown": {"UNKNOWN", 0, errors.New("not a valid log level: 'UNKNOWN'")},
93+
}
94+
95+
for name, testCase := range testCases {
96+
t.Run(name, func(t *testing.T) {
97+
lvl, err := ParseLevel(testCase.input)
98+
assert.Equal(t, testCase.expectedLvl, lvl)
99+
assert.Equal(t, testCase.expectedErr, err)
100+
})
101+
}
102+
}
103+
78104
func loggerFatalTest(t *testing.T, env string, contains string) {
79105
buf := new(bytes.Buffer)
80106
cmd := exec.Command(os.Args[0], "-test.run=TestFatal")

0 commit comments

Comments
 (0)