-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
99 lines (84 loc) · 1.82 KB
/
log.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
package client
import (
"encoding/json"
"io"
"log"
"os"
)
var (
DefaultLogger = NewLogger(os.Stderr, LevelWarn)
LevelTrace LogLevel = 50
LevelDebug LogLevel = 40
LevelInfo LogLevel = 30
LevelWarn LogLevel = 20
LevelError LogLevel = 10
)
type LogLevel int
type Logger interface {
WithField(name string, value interface{}) Logger
Trace(msg string)
Debug(msg string)
Info(msg string)
Warn(msg string)
Error(msg string)
}
type logger struct {
Writer io.Writer
fields []func(map[string]interface{})
logger *log.Logger
level LogLevel
}
func NewLogger(w io.Writer, lvl LogLevel) *logger {
return &logger{logger: log.New(w, "", log.LstdFlags), level: lvl}
}
var _ Logger = &logger{}
func (l *logger) WithField(name string, value interface{}) Logger {
newL := *l
newL.fields = append(newL.fields, func(m map[string]interface{}) {
m[name] = value
})
return &newL
}
func (l *logger) Trace(msg string) { l.log(LevelTrace, msg) }
func (l *logger) Debug(msg string) { l.log(LevelDebug, msg) }
func (l *logger) Info(msg string) { l.log(LevelInfo, msg) }
func (l *logger) Warn(msg string) { l.log(LevelWarn, msg) }
func (l *logger) Error(msg string) { l.log(LevelError, msg) }
func (l *logger) log(lvl LogLevel, msg string) {
if lvl > l.level {
return
}
m := make(map[string]interface{}, len(l.fields))
for _, f := range l.fields {
f(m)
}
var (
b []byte
err error
)
if len(l.fields) > 0 {
b, err = json.Marshal(m)
if err != nil {
println("Logger error: " + err.Error())
return
}
} else {
b = []byte(`{}`)
}
var lvlStr string
switch lvl {
case LevelTrace:
lvlStr = "TRACE"
case LevelDebug:
lvlStr = "DEBUG"
case LevelInfo:
lvlStr = "INFO"
case LevelWarn:
lvlStr = "WARN"
case LevelError:
lvlStr = "ERROR"
default:
lvlStr = "LOG"
}
l.logger.Println(lvlStr, msg, string(b))
}