-
Notifications
You must be signed in to change notification settings - Fork 32
/
level.go
139 lines (127 loc) · 2.36 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package logging
import (
"encoding/json"
"fmt"
"strings"
)
const alignedStringLen = 5
type Level int
const (
Off Level = iota
Fatal
Error
Warn
Info
Trace
Debug
Verbo
)
const (
fatalStr = "FATAL"
errorStr = "ERROR"
warnStr = "WARN"
infoStr = "INFO"
traceStr = "TRACE"
debugStr = "DEBUG"
verboStr = "VERBO"
offStr = "OFF"
unknownStr = "UNKNO"
)
// Inverse of Level.String()
func ToLevel(l string) (Level, error) {
switch strings.ToUpper(l) {
case offStr:
return Off, nil
case fatalStr:
return Fatal, nil
case errorStr:
return Error, nil
case warnStr:
return Warn, nil
case infoStr:
return Info, nil
case traceStr:
return Trace, nil
case debugStr:
return Debug, nil
case verboStr:
return Verbo, nil
default:
return Off, fmt.Errorf("unknown log level: %q", l)
}
}
func (l Level) Color() Color {
switch l {
case Fatal:
return Red
case Error:
return Orange
case Warn:
return Yellow
case Info:
// Rather than using white, use the default to better support terminals
// with a white background.
return Reset
case Trace:
return LightPurple
case Debug:
return LightBlue
case Verbo:
return LightGreen
default:
return Reset
}
}
func (l Level) String() string {
switch l {
case Fatal:
return fatalStr
case Error:
return errorStr
case Warn:
return warnStr
case Info:
return infoStr
case Trace:
return traceStr
case Debug:
return debugStr
case Verbo:
return verboStr
case Off:
return offStr
default:
// This should never happen
return unknownStr
}
}
// String representation of this level as it will appear
// in log files and in logs displayed to screen.
// The returned value has length [alignedStringLen].
func (l Level) AlignedString() string {
s := l.String()
sLen := len(s)
switch {
case sLen < alignedStringLen:
// Pad with spaces on the right
return fmt.Sprintf("%s%s", s, strings.Repeat(" ", alignedStringLen-sLen))
case sLen == alignedStringLen:
return s
default:
return s[:alignedStringLen]
}
}
func (l Level) MarshalJSON() ([]byte, error) {
return json.Marshal(l.String())
}
func (l *Level) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
var err error
*l, err = ToLevel(str)
return err
}