/
logger.go
93 lines (75 loc) · 1.86 KB
/
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
package ls
import (
"encoding/json"
"log"
"runtime/debug"
"time"
)
type Logger interface {
Debug(map[string]interface{})
Info(map[string]interface{})
Error(map[string]interface{})
}
type nopLogger struct{}
func (l *nopLogger) Debug(map[string]interface{}) {}
func (l *nopLogger) Info(map[string]interface{}) {}
func (l *nopLogger) Error(map[string]interface{}) {}
type LogLevel int8
const (
LogLevelError LogLevel = iota
LogLevelInfo
LogLevelDebug
)
func (l LogLevel) String() string {
switch l {
case LogLevelInfo:
return "INFO"
case LogLevelDebug:
return "DEBUG"
case LogLevelError:
return "ERROR"
default:
return ""
}
}
type DefaultLogger struct {
Level LogLevel
Trace bool
}
var DefaultLogLevel = LogLevelError
func NewDefaultLogger() *DefaultLogger {
return &DefaultLogger{Level: DefaultLogLevel}
}
func (l DefaultLogger) Info(properties map[string]interface{}) {
l.print(LogLevelInfo, properties)
}
func (l DefaultLogger) Debug(properties map[string]interface{}) {
l.print(LogLevelDebug, properties)
}
func (l DefaultLogger) Error(properties map[string]interface{}) {
l.print(LogLevelError, properties)
}
func (l DefaultLogger) print(level LogLevel, properties map[string]interface{}) {
if level > l.Level {
return
}
aux := struct {
Level string `json:"level"`
Time string `json:"time"`
Properties map[string]interface{} `json:"properties,omitempty"`
Trace string `json:"trace,omitempty"`
}{
Level: level.String(),
Time: time.Now().UTC().Format(time.RFC3339),
Properties: properties,
}
if level <= LogLevelError || l.Trace {
aux.Trace = string(debug.Stack())
}
var line []byte
line, err := json.Marshal(aux)
if err != nil {
line = []byte(LogLevelError.String() + ": unable to marshal log message: " + err.Error())
}
log.Println(string(line))
}