-
Notifications
You must be signed in to change notification settings - Fork 12
/
levels.go
99 lines (90 loc) · 2 KB
/
levels.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package xlog
import (
"bytes"
"fmt"
"strconv"
)
// Level defines log levels
type Level int
// Log levels
const (
LevelDebug Level = iota
LevelInfo
LevelWarn
LevelError
LevelFatal
)
// Log level strings
var (
levelDebug = "debug"
levelInfo = "info"
levelWarn = "warn"
levelError = "error"
levelFatal = "fatal"
levelBytesDebug = []byte(levelDebug)
levelBytesInfo = []byte(levelInfo)
levelBytesWarn = []byte(levelWarn)
levelBytesError = []byte(levelError)
levelBytesFatal = []byte(levelFatal)
)
// LevelFromString returns the level based on its string representation
func LevelFromString(t string) (Level, error) {
l := Level(0)
err := (&l).UnmarshalText([]byte(t))
return l, err
}
// UnmarshalText lets Level implements the TextUnmarshaler interface used by encoding packages
func (l *Level) UnmarshalText(text []byte) (err error) {
if bytes.Equal(text, levelBytesDebug) {
*l = LevelDebug
} else if bytes.Equal(text, levelBytesInfo) {
*l = LevelInfo
} else if bytes.Equal(text, levelBytesWarn) {
*l = LevelWarn
} else if bytes.Equal(text, levelBytesError) {
*l = LevelError
} else if bytes.Equal(text, levelBytesFatal) {
*l = LevelFatal
} else {
err = fmt.Errorf("Uknown level %v", string(text))
}
return
}
// String returns the string representation of the level.
func (l Level) String() string {
var t string
switch l {
case LevelDebug:
t = levelDebug
case LevelInfo:
t = levelInfo
case LevelWarn:
t = levelWarn
case LevelError:
t = levelError
case LevelFatal:
t = levelFatal
default:
t = strconv.FormatInt(int64(l), 10)
}
return t
}
// MarshalText lets Level implements the TextMarshaler interface used by encoding packages
func (l Level) MarshalText() ([]byte, error) {
var t []byte
switch l {
case LevelDebug:
t = levelBytesDebug
case LevelInfo:
t = levelBytesInfo
case LevelWarn:
t = levelBytesWarn
case LevelError:
t = levelBytesError
case LevelFatal:
t = levelBytesFatal
default:
t = []byte(strconv.FormatInt(int64(l), 10))
}
return t, nil
}