-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlevel.go
78 lines (68 loc) · 1.48 KB
/
level.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package log
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
)
// Level is the level of the logger.
type Level uint8
const (
// LevelError is the error level.
LevelError Level = iota
// LevelWarn is the warn level.
LevelWarn
// LevelInfo is the info level.
LevelInfo
// LevelDebug is the debug level.
LevelDebug
)
func (level Level) String() (s string) {
switch level {
case LevelError:
return "ERROR"
case LevelWarn:
return "WARN"
case LevelInfo:
return "INFO"
case LevelDebug:
return "DEBUG"
default:
panic(fmt.Sprintf("level %d is unknown", level))
}
}
// ColoredString returns the corresponding colored
// string for the level.
func (level Level) ColoredString() (s string) {
attribute := color.Reset
switch level {
case LevelDebug:
attribute = color.FgHiBlue
case LevelInfo:
attribute = color.FgCyan
case LevelWarn:
attribute = color.FgYellow
case LevelError:
attribute = color.FgHiRed
}
c := color.New(attribute)
return c.Sprint(level.String())
}
var (
ErrLevelNotRecognized = errors.New("level is not recognized")
)
// ParseLevel parses a string into a level, and returns an
// error if it fails.
func ParseLevel(s string) (level Level, err error) {
switch strings.ToUpper(s) {
case LevelDebug.String():
return LevelDebug, nil
case LevelInfo.String():
return LevelInfo, nil
case LevelWarn.String():
return LevelWarn, nil
case LevelError.String():
return LevelError, nil
}
return 0, fmt.Errorf("%w: %s", ErrLevelNotRecognized, s)
}