-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevel.go
More file actions
133 lines (120 loc) · 2.34 KB
/
level.go
File metadata and controls
133 lines (120 loc) · 2.34 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
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
package log
import (
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
)
// Level represents the logging level.
// -4: Debug
// 0: Info
// 4: Warn
// 8: Error
// 12: Critical
type Level int
const (
LevelDebug = Level(slog.LevelDebug)
LevelInfo = Level(slog.LevelInfo)
LevelWarn = Level(slog.LevelWarn)
LevelError = Level(slog.LevelError)
LevelCrit = Level(slog.Level(12))
)
func LevelFromSlog(l slog.Level) Level {
switch l {
case slog.LevelDebug:
return LevelDebug
case slog.LevelInfo:
return LevelInfo
case slog.LevelWarn:
return LevelWarn
case slog.LevelError:
return LevelError
default:
return Level(l)
}
}
func (l Level) String() string {
switch l {
case LevelDebug:
return "DEBUG"
case LevelInfo:
return "INFO"
case LevelWarn:
return "WARN"
case LevelError:
return "ERROR"
case LevelCrit:
return "CRIT"
default:
if l < LevelInfo {
return "DEBUG+" + strconv.Itoa(int(l-LevelDebug))
}
if l < LevelWarn {
return "INFO+" + strconv.Itoa(int(l-LevelInfo))
}
if l < LevelError {
return "WARN+" + strconv.Itoa(int(l-LevelWarn))
}
return "ERROR+" + strconv.Itoa(int(l-LevelError))
}
}
func (l Level) TerminalString() string {
switch l {
case LevelDebug:
return "DEBUG "
case LevelInfo:
return "INFO "
case LevelWarn:
return "WARN "
case LevelError:
return "ERROR "
case LevelCrit:
return "CRIT "
default:
return "LOG "
}
}
func (l Level) MarshalJSON() ([]byte, error) {
return strconv.AppendQuote(nil, l.String()), nil
}
func (l *Level) UnmarshalJSON(data []byte) error {
s, err := strconv.Unquote(string(data))
if err != nil {
return err
}
return l.parse(s)
}
func (l Level) MarshalText() ([]byte, error) {
return []byte(l.String()), nil
}
func (l *Level) UnmarshalText(data []byte) error {
return l.parse(string(data))
}
func (l *Level) parse(s string) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("slog: level string %q: %w", s, err)
}
}()
name := s
if i := strings.IndexAny(s, "+-"); i >= 0 {
name = s[:i]
}
switch strings.ToUpper(strings.TrimSpace(name)) {
case "DEBUG":
*l = LevelDebug
case "INFO":
*l = LevelInfo
case "WARN":
*l = LevelWarn
case "ERROR":
*l = LevelError
case "CRIT", "CRITICAL":
*l = LevelCrit
default:
return errors.New("unknown name")
}
return nil
}
func (l Level) Level() slog.Level { return slog.Level(l) }