-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlevel.go
More file actions
69 lines (61 loc) · 1.75 KB
/
level.go
File metadata and controls
69 lines (61 loc) · 1.75 KB
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
package log
import (
"bytes"
"fmt"
"strconv"
)
// Level is used to indicate priority or threshold
type Level int
const (
// FatalLevel should be used to communicate when the application has failed
// and is left in an unpredictable state.
FatalLevel Level = iota
// ErrorLevel should be used to communicate when something went wrong in the
// application, but the application can continue.
ErrorLevel
// InfoLevel should be used to communicate when something happened that is
// worth noting.
InfoLevel
// TraceLevel should be used to communicate when something happened.
TraceLevel
)
// LogLevelToString maps log levels to string representations
var LogLevelToString = map[Level]string{
FatalLevel: "Fatal",
ErrorLevel: "Error",
InfoLevel: "Info",
TraceLevel: "Trace",
}
// StringToLogLevel maps string representations to log levels.
var StringToLogLevel = map[string]Level{
"FATAL": FatalLevel,
"ERROR": ErrorLevel,
"INFO": InfoLevel,
"TRACE": TraceLevel,
}
// String represents a Level as a human-readable string instead of the integer value.
func (lvl Level) String() string {
txt, ok := LogLevelToString[lvl]
if !ok {
txt = strconv.Itoa(int(lvl))
}
return txt
}
// MarshalText returns a human-readable text representation of a Level.
func (lvl Level) MarshalText() ([]byte, error) {
return []byte(lvl.String()), nil
}
// UnmarshalText assigns a Level according to a text representation of either
// the human-readable string or integer value of a Level.
func (lvl *Level) UnmarshalText(raw []byte) error {
level, ok := StringToLogLevel[string(bytes.ToUpper(raw))]
if !ok {
lvlInt, err := strconv.Atoi(string(raw))
if err != nil {
return fmt.Errorf("level not found: %+v", err)
}
level = Level(lvlInt)
}
*lvl = level
return nil
}