Skip to content

Commit

Permalink
feat: Add LevelFromString function.
Browse files Browse the repository at this point in the history
  • Loading branch information
iamd3vil committed Jul 11, 2022
1 parent fa8a1fd commit 28c116a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
17 changes: 17 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,23 @@ func (l Level) String() string {
}
}

func LevelFromString(lvl string) (Level, error) {
switch lvl {
case "debug":
return DebugLevel, nil
case "info":
return InfoLevel, nil
case "warn":
return WarnLevel, nil
case "error":
return ErrorLevel, nil
case "fatal":
return FatalLevel, nil
default:
return 0, fmt.Errorf("invalid level")
}
}

// Debug emits a debug log line.
func (l Logger) Debug(msg string, fields ...any) {
l.handleLog(msg, DebugLevel, fields...)
Expand Down
26 changes: 19 additions & 7 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package logf
import (
"bytes"
"errors"
"fmt"
"log"
"strconv"
"sync"
Expand All @@ -17,12 +18,12 @@ func TestLogFormatWithEnableCaller(t *testing.T) {

l.Info("hello world")
require.Contains(t, buf.String(), `level=info message="hello world" caller=`)
require.Contains(t, buf.String(), `logf/log_test.go:18`)
require.Contains(t, buf.String(), `logf/log_test.go:19`)
buf.Reset()

lC := New(Opts{Writer: buf, EnableCaller: true, EnableColor: true})
lC.Info("hello world")
require.Contains(t, buf.String(), `logf/log_test.go:24`)
require.Contains(t, buf.String(), `logf/log_test.go:25`)
buf.Reset()
}

Expand All @@ -32,11 +33,11 @@ func TestLevelParsing(t *testing.T) {
Lvl Level
Num int
}{
{"debug", DebugLevel, 0},
{"info", InfoLevel, 1},
{"warn", WarnLevel, 2},
{"error", ErrorLevel, 3},
{"fatal", FatalLevel, 4},
{"debug", DebugLevel, 1},
{"info", InfoLevel, 2},
{"warn", WarnLevel, 3},
{"error", ErrorLevel, 4},
{"fatal", FatalLevel, 5},
}

for _, c := range cases {
Expand All @@ -45,6 +46,17 @@ func TestLevelParsing(t *testing.T) {
})
}

// Test LevelFromString.
for _, c := range cases {
t.Run(fmt.Sprintf("from-string-%v", c.String), func(t *testing.T) {
str, err := LevelFromString(c.String)
if err != nil {
t.Fatalf("error parsing level: %v", err)
}
require.Equal(t, c.Lvl, str, "level should be equal")
})
}

// Check for an invalid case.
t.Run("invalid", func(t *testing.T) {
var invalidLvl Level = 10
Expand Down

0 comments on commit 28c116a

Please sign in to comment.