This repository has been archived by the owner on Jan 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
285 lines (234 loc) · 6.63 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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package logger
import (
"context"
"fmt"
"os"
"sync"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type (
// Logger logger option
Logger struct {
Level string `config:"level" help:"Levels: debug,info,warn,error,dpanic,panic,fatal"`
Encoding string `config:"encoding" help:"PS: console or json"`
TraceUID string `config:"traceUid" help:"Name as trace uid in context"`
TraceRequestID string `config:"traceRequestId" help:"Name as trace requestId in context"`
TraceSpanID string `config:"traceSpanId" help:"Name as trace spanId in context"`
TraceBizID string `config:"traceBizId" help:"Name as trace spanId in context"`
CallerKey string `config:"callerKey" help:"caller key in log"`
CallerSkip int `config:"callerSkip" help:"AddCallerSkip increases the number of callers skipped by caller annotation"`
FilterSpecs []string `config:"filterSpecs" help:"filter rules, split by ==>. eg: old ==> new"`
*zap.SugaredLogger
}
)
var (
// Default the default logger
Default = &Logger{}
global = Default
once = sync.Once{}
locker = sync.Mutex{}
)
func init() {
if Default.SugaredLogger == nil {
l, err := zap.NewDevelopment()
if err != nil {
panic(err)
}
Default.SugaredLogger = l.Sugar()
}
}
// Name logger config name
func (logger *Logger) Name() string {
return "logger"
}
// ConfigWillLoad logger config
func (logger *Logger) ConfigWillLoad(context.Context) {
if logger.Level == "" {
logger.Level = "debug"
}
if logger.Encoding == "" {
logger.Encoding = "console"
}
if logger.TraceUID == "" {
logger.TraceUID = "uid"
}
if logger.TraceRequestID == "" {
logger.TraceRequestID = "requestId"
}
if logger.TraceSpanID == "" {
logger.TraceSpanID = "traceSpanId"
}
if logger.TraceBizID == "" {
logger.TraceBizID = "traceBizId"
}
logger.apply()
}
// ConfigDidLoad did load
func (logger *Logger) ConfigDidLoad(ctx context.Context) {
logger.apply()
once.Do(func() {
global = &Logger{
Level: Default.Level,
Encoding: Default.Encoding,
TraceUID: Default.TraceUID,
TraceRequestID: Default.TraceRequestID,
SugaredLogger: Default.SugaredLogger.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar(),
}
})
}
func (logger *Logger) apply() {
locker.Lock()
defer locker.Unlock()
cfg := &zap.Config{
Development: false,
Level: newAtomicLevelAt(logger.Level),
Encoding: logger.Encoding,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
MessageKey: "msg",
StacktraceKey: "stacktrace",
CallerKey: logger.CallerKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
log, err := cfg.Build(
zap.AddCallerSkip(logger.CallerSkip),
zap.WrapCore(func(c zapcore.Core) zapcore.Core {
var ws *filterWriter
var enc zapcore.Encoder
if logger.Encoding == "console" {
enc = zapcore.NewConsoleEncoder(cfg.EncoderConfig)
} else {
enc = zapcore.NewJSONEncoder(cfg.EncoderConfig)
}
if logger.Level == "debug" || logger.Level == "info" || logger.Level == "warn" {
ws = newFilterWriter(os.Stdout, newFilterBySlice(logger.FilterSpecs)...)
} else {
ws = newFilterWriter(os.Stderr, newFilterBySlice(logger.FilterSpecs)...)
}
return zapcore.NewCore(enc, ws, cfg.Level)
}),
)
if err != nil {
panic(err)
}
defer log.Sync()
logger.SugaredLogger = log.Sugar()
}
func (logger *Logger) TraceRaw(ctx context.Context) *zap.Logger {
return trace(ctx, logger).Desugar()
}
// Trace logger with requestId and uid
func (logger *Logger) Trace(ctx context.Context) *zap.SugaredLogger {
return trace(ctx, logger)
}
func TraceRaw(ctx context.Context) *zap.Logger {
return trace(ctx, Default).Desugar()
}
func Trace(ctx context.Context) *zap.SugaredLogger {
return trace(ctx, Default)
}
func DPanic(args ...interface{}) {
global.DPanic(args...)
}
func DPanicf(template string, args ...interface{}) {
global.DPanicf(template, args...)
}
func DPanicw(msg string, keysAndValues ...interface{}) {
global.DPanicw(msg, keysAndValues...)
}
func Debug(args ...interface{}) {
global.Debug(args...)
}
func Debugf(template string, args ...interface{}) {
global.Debugf(template, args...)
}
func Debugw(msg string, keysAndValues ...interface{}) {
global.Debugw(msg, keysAndValues...)
}
func Desugar() *zap.Logger {
return global.Desugar()
}
func Error(args ...interface{}) {
global.Error(args...)
}
func Errorf(template string, args ...interface{}) {
global.Errorf(template, args...)
}
func Errorw(msg string, keysAndValues ...interface{}) {
global.Errorw(msg, keysAndValues...)
}
func Fatal(args ...interface{}) {
global.Fatal(args...)
}
func Fatalf(template string, args ...interface{}) {
global.Fatalf(template, args...)
}
func Fatalw(msg string, keysAndValues ...interface{}) {
global.Fatalw(msg, keysAndValues...)
}
func Info(args ...interface{}) {
global.Info(args...)
}
func Infof(template string, args ...interface{}) {
global.Infof(template, args...)
}
func Infow(msg string, keysAndValues ...interface{}) {
global.Infow(msg, keysAndValues...)
}
func Named(name string) *zap.SugaredLogger {
return global.Named(name)
}
func Panic(args ...interface{}) {
global.Panic(args...)
}
func Panicf(template string, args ...interface{}) {
global.Panicf(template, args...)
}
func Panicw(msg string, keysAndValues ...interface{}) {
global.Panicw(msg, keysAndValues...)
}
func Sync() error {
return global.Sync()
}
func Warn(args ...interface{}) {
global.Warn(args...)
}
func Warnf(template string, args ...interface{}) {
global.Warnf(template, args...)
}
func Warnw(msg string, keysAndValues ...interface{}) {
global.Warnw(msg, keysAndValues...)
}
func With(args ...interface{}) *zap.SugaredLogger {
return global.With(args...)
}
func trace(ctx context.Context, logger *Logger) *zap.SugaredLogger {
var uid, requestID, spanId, bizId string
if uidStr, ok := ctx.Value(logger.TraceUID).(string); ok {
uid = uidStr
}
if requestIDStr, ok := ctx.Value(logger.TraceRequestID).(string); ok {
requestID = requestIDStr
}
if spanIdStr, ok := ctx.Value(logger.TraceSpanID).(string); ok {
spanId = spanIdStr
}
if bizIdStr, ok := ctx.Value(logger.TraceBizID).(string); ok {
bizId = bizIdStr
}
return logger.SugaredLogger.Named(fmt.Sprintf("[%s][%s][%s][%s]", uid, requestID, spanId, bizId))
}