-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathlevel.go
More file actions
98 lines (83 loc) · 1.96 KB
/
level.go
File metadata and controls
98 lines (83 loc) · 1.96 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
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
package logrus
import (
"strings"
"sync"
)
const (
ansiReset = "\x1b[0m" // reset attributes
ansiRed = "\x1b[31m" // red
ansiYellow = "\x1b[33m" // yellow
ansiCyan = "\x1b[36m" // cyan
ansiWhite = "\x1b[37m" // white (light gray)
)
type lvlPrefix struct {
full string
truncated string
padded string
}
func colorize(level Level, s string) string {
color := ansiCyan
switch level {
case DebugLevel, TraceLevel:
color = ansiWhite
case WarnLevel:
color = ansiYellow
case ErrorLevel, FatalLevel, PanicLevel:
color = ansiRed
case InfoLevel:
color = ansiCyan
}
return color + s + ansiReset
}
func formatLevel(level Level, disableTrunc, pad bool, maxLen int) string {
upper := strings.ToUpper(level.String())
if pad && maxLen > len(upper) {
upper += strings.Repeat(" ", maxLen-len(upper))
}
if !pad && !disableTrunc && len(upper) > 4 {
upper = upper[:4]
}
return colorize(level, upper)
}
var levelPrefixOnce = sync.OnceValues(func() (map[Level]lvlPrefix, lvlPrefix) {
var maxLevel Level
maxLen := 0
for _, lvl := range AllLevels {
if lvl > maxLevel {
maxLevel = lvl
}
if l := len(lvl.String()); l > maxLen {
maxLen = l
}
}
prefix := make(map[Level]lvlPrefix, len(AllLevels))
for _, lvl := range AllLevels {
prefix[lvl] = lvlPrefix{
full: formatLevel(lvl, true, false, maxLen),
truncated: formatLevel(lvl, false, false, maxLen),
padded: formatLevel(lvl, true, true, maxLen),
}
}
unknownLevel := maxLevel + 1
unknown := lvlPrefix{
full: formatLevel(unknownLevel, true, false, maxLen),
truncated: formatLevel(unknownLevel, false, false, maxLen),
padded: formatLevel(unknownLevel, true, true, maxLen),
}
return prefix, unknown
})
func levelPrefix(level Level, disableTrunc, pad bool) string {
prefix, unknown := levelPrefixOnce()
p, ok := prefix[level]
if !ok {
p = unknown
}
switch {
case pad:
return p.padded
case !disableTrunc:
return p.truncated
default:
return p.full
}
}