-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
105 lines (90 loc) · 2.32 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
94
95
96
97
98
99
100
101
102
103
104
105
package metrics
import (
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Logger struct {
log *zap.Logger
}
func NewLogger(logLevel string) *Logger {
logConfig := zap.Config{
OutputPaths: []string{"stdout"},
Level: zap.NewAtomicLevelAt(getLogLevel(logLevel)),
Encoding: "json",
EncoderConfig: zapcore.EncoderConfig{
LevelKey: "level",
TimeKey: "time",
MessageKey: "message",
CallerKey: "caller",
StacktraceKey: "stacktrace",
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
}
log, err := logConfig.Build(zap.AddCallerSkip(1))
if err != nil {
log.Panic(err.Error())
}
return &Logger{log: log}
}
func escapeString(str *string) {
replacer := strings.NewReplacer("\n", "", "\r", "")
*str = replacer.Replace(*str)
}
func escapeStringTags(tags *[]zap.Field) {
for i, tag := range *tags {
if tag.Type == zapcore.StringType {
escapeString(&(*tags)[i].String)
}
}
}
func (l *Logger) Info(message string, tags ...zap.Field) {
escapeStringTags(&tags)
escapeString(&message)
l.log.Info(message, tags...)
}
func (l *Logger) Panic(message string, err error, tags ...zap.Field) {
escapeString(&message)
escapeStringTags(&tags)
tags = append(tags, zap.NamedError("error", err))
l.log.Panic(message, tags...)
}
func (l *Logger) Fatal(message string, err error, tags ...zap.Field) {
escapeString(&message)
escapeStringTags(&tags)
tags = append(tags, zap.NamedError("error", err))
l.log.Fatal(message, tags...)
}
func (l *Logger) Warn(message string, tags ...zap.Field) {
escapeString(&message)
escapeStringTags(&tags)
l.log.Warn(message, tags...)
}
func (l *Logger) Error(message string, err error, tags ...zap.Field) {
escapeString(&message)
escapeStringTags(&tags)
tags = append(tags, zap.NamedError("error", err))
l.log.Error(message, tags...)
}
func (l *Logger) Sync() {
l.log.Sync()
}
func (l *Logger) Debug(message string, tags ...zap.Field) {
escapeString(&message)
escapeStringTags(&tags)
l.log.Debug(message, tags...)
}
func getLogLevel(level string) zapcore.Level {
switch strings.ToLower(level) {
case "info":
return zapcore.InfoLevel
case "error":
return zapcore.ErrorLevel
case "debug":
return zapcore.DebugLevel
default:
return zapcore.InfoLevel
}
}