-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
479 lines (402 loc) · 14.4 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package log
import (
"context"
"fmt"
"github.com/marmotedu/log/klog"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"log"
"sync"
)
// InfoLogger represent the ability to log non-error message, at a particular verbosity.
type InfoLogger interface {
// Info logs a non-error message with the given key/value pairs as context.
//
// The msg argument should be used to add some constant description to
// the log line. The key/value pairs can then be used to add additional
// variable information. The key/value pairs should alternate string
// keys and arbitrary values.
Info(msg string, fields ...Field)
Infof(msg string, args ...interface{})
Infow(msg string, keyAndValues ...interface{})
// Enabled tests whether this InfoLogger is enabled. For example,
// commandline flags might be used to set the logging verbosity and disable
// some info logs.
Enabled() bool
}
type Logger interface {
// All Loggers implement InfoLogger. Calling InfoLogger methods directly on
// a Logger value is equivalent to calling them on a V(0) InfoLogger. For
// example, logger.Info() produces the same result as logger.V(0).Info.
InfoLogger
Debug(msg string, fields ...Field)
Debugf(format string, v ...interface{})
Debugw(msg string, keysAndValues ...interface{})
Warn(msg string, fields ...Field)
Warnf(format string, v ...interface{})
Warnw(msg string, keysAndValues ...interface{})
Error(msg string, fields ...Field)
Errorf(format string, v ...interface{})
Errorw(msg string, keysAndValues ...interface{})
Panic(msg string, fields ...Field)
Panicf(format string, v ...interface{})
Panicw(msg string, keysAndValues ...interface{})
Fatal(msg string, fields ...Field)
Fatalf(format string, v ...interface{})
Fatalw(msg string, keysAndValues ...interface{})
// All Loggers implement InfoLogger. Calling InfoLogger methods directly on
// a Logger value is equivalent to calling them on a V(0) InfoLogger. For
// example, logger.Info() produces the same result as logger.V(0).Info.
V(level Level) InfoLogger
Write(p []byte) (n int, err error)
// WithValues adds some key-value pairs of context to a logger.
// See Info for documentation on how key/value pairs work.
WithValues(keysAndValues ...interface{}) Logger
// WithName adds a new element to the logger's name.
// Successive calls with WithName continue to append
// suffixes to the logger's name. It's strongly recommended
// that name segments contain only letters, digits, and hyphens
// (see the package documentation for more information).
WithName(name string) Logger
// WithContext returns a copy of context in which the log value is set.
WithContext(ctx context.Context) context.Context
// Flush calls the underlying Core's Sync method, flushing any buffered
// log entries. Applications should take care to call Sync before exiting.
Flush()
}
// noopInfoLogger is a logr.InfoLogger that's always disabled, and does nothing.
type noopInfoLogger struct{}
func (l *noopInfoLogger) Enabled() bool { return false }
func (l *noopInfoLogger) Info(_ string, _ ...Field) {}
func (l *noopInfoLogger) Infof(_ string, _ ...interface{}) {}
func (l *noopInfoLogger) Infow(_ string, _ ...interface{}) {}
var disableInfoLogger = &noopInfoLogger{}
type infoLogger struct {
level zapcore.Level
log *zap.Logger
}
func (l *infoLogger) Enabled() bool { return true }
func (l *infoLogger) Info(msg string, fields ...Field) {
if ce := l.log.Check(l.level, msg); ce != nil {
ce.Write(fields...)
}
}
func (l *infoLogger) Infof(format string, args ...interface{}) {
if ce := l.log.Check(l.level, fmt.Sprintf(format, args...)); ce != nil {
ce.Write()
}
}
func (l *infoLogger) Infow(msg string, keysAndValues ...interface{}) {
if ce := l.log.Check(l.level, msg); ce != nil {
ce.Write(handleFields(l.log, keysAndValues)...)
}
}
// handleFields converts a bunch of arbitrary key-value pairs into Zap fields. It takes
// additional pre-converted Zap fields, for use with automatically attached fields, like
// `error`.
func handleFields(l *zap.Logger, args []interface{}, additional ...zap.Field) []zap.Field {
// a slightly modified version of zap.SugaredLogger.sweetenFields
if len(args) == 0 {
return additional
}
// unlike Zap, we can be pretty sure users aren't passing structured
// fields (since logr has no concept of that), so guess that we need a
// little less space.
fields := make([]zap.Field, 0, len(args)/2+len(additional))
for i := 0; i < len(args); i++ {
// check just in case for strongly-typed Zap fields, which is illegal (since
// it breaks implementation agnosticism), so we can give a better error message.
if _, ok := args[i].(zap.Field); ok {
l.DPanic("strongly-typed Zap Field passed to logr", zap.Any("zap field", args[i]))
break
}
// make sure this isn't a mismatched key
if i == len(args)-1 {
l.DPanic("odd number of arguments passed as key-value pairs for logging", zap.Any("ignored key", args[i]))
break
}
// process a key-value pair,
// ensuring that the key is a string
key, val := args[i], args[i+1]
keyStr, isString := key.(string)
if !isString {
// if the key isn't a string, DPanic and stop logging
l.DPanic(
"non-string key argument passed to logging, ignoring all later arguments",
zap.Any("invalid key", key),
)
break
}
fields = append(fields, zap.Any(keyStr, val))
i += 2
}
return append(fields, additional...)
}
// zapLogger is a logr.Logger that uses Zap to log.
type zapLogger struct {
// NB: this looks very similar to zap.SugaredLogger, but
// deals with our desire to have multiple verbosity levels.
zapLogger *zap.Logger
infoLogger
}
var _ Logger = &zapLogger{}
var (
std = New(NewOptions())
mu sync.Mutex
)
// Init initializes logger with specified options.
func Init(opts *Options) {
mu.Lock()
defer mu.Unlock()
std = New(opts)
}
// New create logger by opts which can custmoized by command arguments.
func New(opts *Options) *zapLogger {
if opts == nil {
opts = NewOptions()
}
// validate the level in Options
var zapLevel zapcore.Level
if err := zapLevel.UnmarshalText([]byte(opts.Level)); err != nil {
zapLevel = zapcore.InfoLevel
}
levelEncoder := zapcore.CapitalLevelEncoder
if opts.Format == consoleFormat && opts.EnableColor {
levelEncoder = zapcore.CapitalColorLevelEncoder
}
// setup encoder config
encoderConfig := zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "timestamp",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: "stacktrace",
EncodeLevel: levelEncoder,
EncodeTime: timeEncoder,
EncodeDuration: milliSecondDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
// setup logger config
loggerConfig := zap.Config{
Level: zap.NewAtomicLevelAt(zapLevel),
Development: opts.Development,
DisableCaller: opts.DisableCaller,
DisableStacktrace: opts.DisableStacktrace,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: opts.Format,
EncoderConfig: encoderConfig,
OutputPaths: opts.OutputPaths,
ErrorOutputPaths: opts.ErrorOutputPaths,
}
var err error
l, err := loggerConfig.Build(zap.AddStacktrace(zapcore.PanicLevel), zap.AddCallerSkip(1))
if err != nil {
panic(err)
}
logger := &zapLogger{
zapLogger: l.Named(opts.Name),
infoLogger: infoLogger{
level: zapcore.InfoLevel,
log: l,
},
}
klog.InitLogger(l)
zap.RedirectStdLog(l)
return logger
}
// SugaredLogger returns global sugared logger.
func SugaredLogger() *zap.SugaredLogger {
return std.zapLogger.Sugar()
}
// StdErrLogger returns logger of standard library which writes to supplied zap
// logger at error level.
func StdErrLogger() *log.Logger {
if std == nil {
return nil
}
if l, err := zap.NewStdLogAt(std.zapLogger, zapcore.ErrorLevel); err == nil {
return l
}
return nil
}
// StdInfoLogger returns logger of standard library which writes to supplied zap
// logger at info level.
func StdInfoLogger() *log.Logger {
if std == nil {
return nil
}
if l, err := zap.NewStdLogAt(std.zapLogger, zapcore.InfoLevel); err == nil {
return l
}
return nil
}
// V return a leveled InfoLogger.
func V(level Level) InfoLogger { return std.V(level) }
func (l *zapLogger) V(level Level) InfoLogger {
if l.zapLogger.Core().Enabled(level) {
return &infoLogger{
level: level,
log: l.zapLogger,
}
}
return disableInfoLogger
}
func (l *zapLogger) Write(p []byte) (n int, err error) {
l.zapLogger.Info(string(p))
return len(p), nil
}
// WithValues creates a child logger and adds Zap fields to it.
func WithValues(keysAndValues ...interface{}) Logger {
return std.WithValues(keysAndValues...)
}
func (l *zapLogger) WithValues(keysAndValues ...interface{}) Logger {
newLogger := l.zapLogger.With(handleFields(l.zapLogger, keysAndValues)...)
return NewLogger(newLogger)
}
// WithName adds a new path segment to the logger's name. Segments are joined by
// periods. By default, Loggers are unnamed.
func WithName(name string) Logger {
return std.WithName(name)
}
func (l *zapLogger) WithName(name string) Logger {
newLogger := l.zapLogger.Named(name)
return NewLogger(newLogger)
}
// NewLogger creates a new logr.Logger using the given Zap Logger to log.
func NewLogger(l *zap.Logger) Logger {
return &zapLogger{
zapLogger: l,
infoLogger: infoLogger{
log: l,
level: zap.InfoLevel,
},
}
}
// Flush calls the underlying Core's Sync method, flushing any buffered
// log entries. Applications should take care to call Sync before exiting.
func Flush() { std.Flush() }
func (l *zapLogger) Flush() { _ = l.zapLogger.Sync() }
func ZapLogger() *zap.Logger {
return std.zapLogger
}
func CheckIntLevel(level int32) bool {
var lvl zapcore.Level
if level < 5 {
lvl = zapcore.InfoLevel
} else {
lvl = zapcore.DebugLevel
}
ce := std.zapLogger.Check(lvl, "")
return ce != nil
}
// Info method output info level log.
func Info(msg string, fields ...Field) { std.Info(msg, fields...) }
func (l *zapLogger) Info(msg string, fields ...Field) {
l.zapLogger.Info(msg, fields...)
}
// Infof method output info level log.
func Infof(msg string, args ...interface{}) { std.Infof(msg, args...) }
func (l *zapLogger) Infof(msg string, args ...interface{}) {
l.zapLogger.Sugar().Infof(msg, args...)
}
// Infow method output info level log.
func Infow(msg string, keysAndValues ...interface{}) { std.Infow(msg, keysAndValues...) }
func (l *zapLogger) Infow(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Infow(msg, keysAndValues...)
}
// Debug method output debug level log.
func Debug(msg string, fields ...Field) { std.Debug(msg, fields...) }
func (l *zapLogger) Debug(msg string, fields ...Field) {
l.zapLogger.Debug(msg, fields...)
}
// Debugf method output debug level log.
func Debugf(format string, v ...interface{}) { std.Debugf(format, v...) }
func (l *zapLogger) Debugf(format string, v ...interface{}) {
l.zapLogger.Sugar().Debugf(format, v...)
}
// Debugw method output debug level log.
func Debugw(msg string, keysAndValues ...interface{}) { std.Debugw(msg, keysAndValues...) }
func (l *zapLogger) Debugw(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Debugw(msg, keysAndValues...)
}
// Warn method output warning level log.
func Warn(msg string, fields ...Field) { std.Warn(msg, fields...) }
func (l *zapLogger) Warn(msg string, fields ...Field) {
l.zapLogger.Warn(msg, fields...)
}
// Warnf method output warning level log.
func Warnf(format string, v ...interface{}) { std.Warnf(format, v...) }
func (l *zapLogger) Warnf(format string, v ...interface{}) {
l.zapLogger.Sugar().Warnf(format, v...)
}
// Warnw method output warning level log.
func Warnw(msg string, keysAndValues ...interface{}) { std.Warnw(msg, keysAndValues...) }
func (l *zapLogger) Warnw(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Warnw(msg, keysAndValues...)
}
// Error method output error level log.
func Error(msg string, fields ...Field) { std.Error(msg, fields...) }
func (l *zapLogger) Error(msg string, fields ...Field) {
l.zapLogger.Error(msg, fields...)
}
// Errorf method output error level log.
func Errorf(format string, v ...interface{}) { std.Errorf(format, v...) }
func (l *zapLogger) Errorf(format string, v ...interface{}) {
l.zapLogger.Sugar().Errorf(format, v...)
}
// Errorw method output error level log.
func Errorw(msg string, keysAndValues ...interface{}) { std.Errorw(msg, keysAndValues...) }
func (l *zapLogger) Errorw(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Errorw(msg, keysAndValues...)
}
// Panic method output panic level log and shutdown application.
func Panic(msg string, fields ...Field) { std.Panic(msg, fields...) }
func (l *zapLogger) Panic(msg string, fields ...Field) {
l.zapLogger.Panic(msg, fields...)
}
// Panicf method output panic level log and shutdown application.
func Panicf(format string, v ...interface{}) { std.Panicf(format, v...) }
func (l *zapLogger) Panicf(format string, v ...interface{}) {
l.zapLogger.Sugar().Panicf(format, v...)
}
// Panicw method output panic level log.
func Panicw(msg string, keysAndValues ...interface{}) { std.Panicw(msg, keysAndValues...) }
func (l *zapLogger) Panicw(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Panicw(msg, keysAndValues...)
}
// Fatal method output fatal level log.
func Fatal(msg string, fields ...Field) { std.Fatal(msg, fields...) }
func (l *zapLogger) Fatal(msg string, fields ...Field) {
l.zapLogger.Fatal(msg, fields...)
}
// Fatalf method output fatal level log.
func Fatalf(format string, v ...interface{}) { std.Fatalf(format, v...) }
func (l *zapLogger) Fatalf(format string, v ...interface{}) {
l.zapLogger.Sugar().Fatalf(format, v...)
}
// Fatalw method output Fatalw level log.
func Fatalw(msg string, keysAndValues ...interface{}) { std.Fatalw(msg, keysAndValues...) }
func (l *zapLogger) Fatalw(msg string, keysAndValues ...interface{}) {
l.zapLogger.Sugar().Fatalw(msg, keysAndValues...)
}
func (l *zapLogger) L(ctx context.Context) *zapLogger {
lg := l.clone()
if requestID := ctx.Value(KeyRequestID); requestID != nil {
lg.zapLogger = lg.zapLogger.With(zap.Any(KeyRequestID, requestID))
}
if username := ctx.Value(KeyUsername); username != nil {
lg.zapLogger = lg.zapLogger.With(zap.Any(KeyUsername, username))
}
if watcherName := ctx.Value(KeyWatcherName); watcherName != nil {
lg.zapLogger = lg.zapLogger.With(zap.Any(KeyWatcherName, watcherName))
}
return lg
}
func (l *zapLogger) clone() *zapLogger {
copy := *l
return ©
}