From ac197786767084a4f62d7aa5c52535ad31731713 Mon Sep 17 00:00:00 2001 From: Bruno Carlin Date: Tue, 25 Jun 2013 16:53:42 +0200 Subject: [PATCH] Add a function to retrieve a log level by name (useful for config) --- logging.go | 10 ++++++++++ logging_test.go | 15 +++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 logging_test.go diff --git a/logging.go b/logging.go index 35a3400..cd63eb3 100644 --- a/logging.go +++ b/logging.go @@ -1,6 +1,7 @@ package logging import ( + "errors" "fmt" "strings" ) @@ -25,6 +26,15 @@ func (l Level) Name() string { return levelNames[l] } +func LevelByName(l string) (Level, error) { + for pos, name := range levelNames { + if name == l { + return Level(pos), nil + } + } + return DEBUG, errors.New(fmt.Sprintf("Invalid log level %s", l)) +} + type Formatter func(*Record) string func GetLogger() (l *Logger) { diff --git a/logging_test.go b/logging_test.go new file mode 100644 index 0000000..1921e0e --- /dev/null +++ b/logging_test.go @@ -0,0 +1,15 @@ +package logging + +import "testing" + +func Test_LevelByName(t *testing.T) { + for _, levelName := range levelNames { + l, e := LevelByName(levelName) + if e != nil { + t.Errorf("level %s not recognized", levelName) + } + if l.Name() != levelName { + t.Errorf("expected '%s', got '%s'", levelName, l.Name()) + } + } +}