From 1214cf5f38393eb96c37df7c6c6add93a3778b43 Mon Sep 17 00:00:00 2001 From: James Goodhouse Date: Thu, 3 Nov 2022 08:52:31 -0700 Subject: [PATCH] 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. --- log/log.go | 19 +++++++++++++++++++ log/log_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/log/log.go b/log/log.go index 25f719a..939fe2d 100644 --- a/log/log.go +++ b/log/log.go @@ -9,6 +9,7 @@ import ( "path" "runtime" "strconv" + "strings" "sync" "sync/atomic" "time" @@ -248,6 +249,24 @@ func Level() Lvl { return global.Level() } +func ParseLevel(lvl string) (Lvl, error) { + switch strings.ToUpper(lvl) { + case "DEBUG": + return DEBUG, nil + case "INFO": + return INFO, nil + case "WARN": + return WARN, nil + case "ERROR": + return ERROR, nil + case "OFF": + return OFF, nil + } + + var l Lvl + return l, fmt.Errorf("not a valid log level: '%s'", lvl) +} + func SetLevel(level Lvl) { global.SetLevel(level) } diff --git a/log/log_test.go b/log/log_test.go index 78d3204..5b2e56e 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -2,6 +2,7 @@ package log import ( "bytes" + "errors" "os" "os/exec" "sync" @@ -75,6 +76,31 @@ func TestFatal(t *testing.T) { loggerFatalTest(t, "fatalf", "fatal-f") } +func TestParseLevel(t *testing.T) { + testCases := map[string]struct { + input string + expectedLvl Lvl + expectedErr error + }{ + "DEBUG": {"DEBUG", DEBUG, nil}, + "INFO": {"INFO", INFO, nil}, + "WARN": {"WARN", WARN, nil}, + "ERROR": {"ERROR", ERROR, nil}, + "OFF": {"OFF", OFF, nil}, + "lowercase": {"debug", DEBUG, nil}, + "mixedcase": {"WaRn", WARN, nil}, + "unknown": {"UNKNOWN", 0, errors.New("not a valid log level: 'UNKNOWN'")}, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + lvl, err := ParseLevel(testCase.input) + assert.Equal(t, testCase.expectedLvl, lvl) + assert.Equal(t, testCase.expectedErr, err) + }) + } +} + func loggerFatalTest(t *testing.T, env string, contains string) { buf := new(bytes.Buffer) cmd := exec.Command(os.Args[0], "-test.run=TestFatal")