-
Notifications
You must be signed in to change notification settings - Fork 303
/
func_logger.go
102 lines (83 loc) · 2.21 KB
/
func_logger.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
package logger
import (
"fmt"
"io"
)
// A logger that writes all of its messages to `write`
type funcLogger struct {
supportsColor bool
level Level
write func(level Level, fields Fields, b []byte) error
fields Fields
}
var _ Logger = funcLogger{}
func NewFuncLogger(supportsColor bool, level Level, write func(level Level, fields Fields, b []byte) error) Logger {
return funcLogger{
supportsColor: supportsColor,
level: level,
write: write,
fields: nil,
}
}
func (l funcLogger) WithFields(fields Fields) Logger {
if len(fields) == 0 {
return l
}
newFields := make(map[string]string, len(l.fields)+len(fields))
for k, v := range l.fields {
newFields[k] = v
}
for k, v := range fields {
newFields[k] = v
}
return funcLogger{
supportsColor: l.supportsColor,
level: l.level,
write: l.write,
fields: newFields,
}
}
func (l funcLogger) Level() Level {
return l.level
}
func (l funcLogger) Warnf(format string, a ...interface{}) {
l.WriteString(WarnLvl, fmt.Sprintf(format+"\n", a...))
}
func (l funcLogger) Errorf(format string, a ...interface{}) {
l.WriteString(ErrorLvl, fmt.Sprintf(format+"\n", a...))
}
func (l funcLogger) Infof(format string, a ...interface{}) {
l.WriteString(InfoLvl, fmt.Sprintf(format+"\n", a...))
}
func (l funcLogger) Verbosef(format string, a ...interface{}) {
l.WriteString(VerboseLvl, fmt.Sprintf(format+"\n", a...))
}
func (l funcLogger) Debugf(format string, a ...interface{}) {
l.WriteString(DebugLvl, fmt.Sprintf(format+"\n", a...))
}
func (l funcLogger) Write(level Level, bytes []byte) {
if l.level.ShouldDisplay(level) {
_ = l.write(level, l.fields, bytes)
}
}
func (l funcLogger) WriteString(level Level, s string) {
if l.level.ShouldDisplay(level) {
_ = l.write(level, l.fields, []byte(s))
}
}
type FuncLoggerWriter struct {
l funcLogger
level Level
}
var _ io.Writer = FuncLoggerWriter{}
func (fw FuncLoggerWriter) Write(b []byte) (int, error) {
fw.l.Write(fw.level, b)
return len(b), nil
}
func (l funcLogger) Writer(level Level) io.Writer {
return FuncLoggerWriter{l, level}
}
func (l funcLogger) SupportsColor() bool {
return l.supportsColor
}
var _ Logger = funcLogger{}