Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ParseLevel func to return level const #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"path"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -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)
}
Expand Down
26 changes: 26 additions & 0 deletions log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log

import (
"bytes"
"errors"
"os"
"os/exec"
"sync"
Expand Down Expand Up @@ -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")
Expand Down