/
pack_zap.go
356 lines (304 loc) · 10.3 KB
/
pack_zap.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
package logger
import (
"fmt"
"github.com/go-logr/logr"
//"github.com/go-logr/zapr"
"go.uber.org/zap"
)
var _ AdaptedLogger = (*packZap)(nil)
// ZapField return a zap field key-value pair
func ZapField(field string, val interface{}) zap.Field {
return zapIt(field, val)
}
// packLogr adapt logr.Loger format like Logger
type packZap struct {
l *zap.Logger
minLevel Level
numericLevelKey string
allowZapFields bool
panicMessages bool
keyAndValues []zap.Field
}
func newPackZap(cfg *Config, options ...Option) *packZap {
opts := append([]Option{
zap.AddCallerSkip(2),
zap.AddStacktrace(zap.DPanicLevel)}, options...)
zapLogger, err := zap.NewDevelopment(opts...)
if err != nil {
panic(err)
}
p := &packZap{
l: zapLogger,
minLevel: _defaultLevel,
allowZapFields: true,
keyAndValues: nil,
}
return p.init(cfg)
}
// init reset the log level of logger
func (p *packZap) init(cfg *Config) *packZap {
lv := _defaultLevel.Int()
env, err := GetLogLevelFromEnv()
switch {
case err == nil:
lv = env
case cfg != nil:
lv = cfg.Level
}
return p.initLevel(lv)
}
func (p *packZap) initLevel(lv int) *packZap {
if err := validateLogLevel(lv); err == nil {
p.minLevel = Level(lv)
p.l.WithOptions(zap.AddCallerSkip(2)).Info("init-logger-level", ZapField("level", lv))
} else {
p.PutError(err, "init-logger-level", zap.Int("level", lv))
}
return p
}
const noLevel = -1
// NOTE: from github.com/go-logr/zapr.Logger
//
// 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 (p *packZap) handleFields(lvl int, args []interface{}, additional ...zap.Field) []zap.Field {
injectNumericLevel := p.numericLevelKey != "" && lvl != noLevel
// a slightly modified version of zap.SugaredLogger.sweetenFields
if len(args) == 0 {
// fast-return if we have no suggared fields and no "v" field.
if !injectNumericLevel {
return additional
}
// Slightly slower fast path when we need to inject "v".
return append(additional, zap.Int(p.numericLevelKey, lvl))
}
// 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.
numFields := len(args)/2 + len(additional)
if injectNumericLevel {
numFields++
}
fields := make([]zap.Field, 0, numFields)
if injectNumericLevel {
fields = append(fields, zap.Int(p.numericLevelKey, lvl))
}
for i := 0; i < len(args); {
// Check just in case for strongly-typed Zap fields,
// which might be illegal (since it breaks
// implementation agnosticism). If disabled, we can
// give a better error message.
if field, ok := args[i].(zap.Field); ok {
if p.allowZapFields {
fields = append(fields, field)
i++
continue
}
if p.panicMessages {
p.l.WithOptions(zap.AddCallerSkip(1)).DPanic("strongly-typed Zap Field passed to logr", zapIt("zap field", args[i]))
}
break
}
// make sure this isn't a mismatched key
if i == len(args)-1 {
if p.panicMessages {
p.l.WithOptions(zap.AddCallerSkip(1)).DPanic("odd number of arguments passed as key-value pairs for logging", zapIt("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
if p.panicMessages {
p.l.WithOptions(zap.AddCallerSkip(1)).DPanic("non-string key argument passed to logging, ignoring all later arguments", zapIt("invalid key", key))
}
break
}
fields = append(fields, zapIt(keyStr, val))
i += 2
}
return append(additional, fields...)
}
func zapIt(field string, val interface{}) zap.Field {
// Handle types that implement logr.Marshaler: log the replacement
// object instead of the original one.
if marshaler, ok := val.(logr.Marshaler); ok {
val = marshaler.MarshalLog()
}
return zap.Any(field, val)
}
func (p *packZap) log(lv Level, format string, fmtArgs []interface{}, context []interface{}) {
if lv <= _maxIgnoreLevel && lv < p.minLevel { //ignore level with too low priority
return
}
msg := format
switch {
case format == "" && len(fmtArgs) > 0:
msg = fmt.Sprint(fmtArgs...)
case format != "" && len(fmtArgs) > 0:
msg = fmt.Sprintf(format, fmtArgs...)
}
args := p.handleFields(lv.Int(), context, p.keyAndValues...)
if cap(p.keyAndValues) < len(args) {
p.keyAndValues = args[:len(p.keyAndValues)]
}
switch lv {
case DebugLevel:
p.l.Debug(msg, args...)
case InfoLevel:
p.l.Info(msg, args...)
case WarnLevel:
p.l.Warn(msg, args...)
case ErrorLevel:
p.l.Error(msg, args...)
case DPanicLevel:
p.l.DPanic(msg, args...)
case PanicLevel:
p.l.Panic(msg, args...)
case FatalLevel:
p.l.Fatal(msg, args...)
}
}
func (p *packZap) clone() *packZap {
return &packZap{
l: p.l,
minLevel: p.minLevel,
allowZapFields: p.allowZapFields,
keyAndValues: append([]zap.Field(nil), p.keyAndValues...),
}
}
// WithValues returns a new Logger with additional key/value pairs.
func (p *packZap) WithValues(keyAndValues ...interface{}) AdaptedLogger {
n := p.clone()
n.l = p.l.With(p.handleFields(noLevel, keyAndValues)...)
return n
}
// WithName returns a new Logger with the specified name appended.
func (p *packZap) WithName(name string) AdaptedLogger {
n := p.clone()
n.l = p.l.Named(name)
return n
}
// WithLevel returns a new Logger with the specified level filter.
func (p *packZap) WithLevel(level Level) AdaptedLogger {
return p.clone().initLevel(level.Int())
}
// WithOptions clones the current Logger, applies the supplied Options, and
// returns the resulting Logger. It's safe to use concurrently.
func (p *packZap) WithOptions(opts ...Option) AdaptedLogger {
n := p.clone()
n.l = p.l.WithOptions(opts...)
return n
}
// PutError write log with error
func (p *packZap) PutError(err error, msg string, keyAndValues ...interface{}) {
if err != nil {
keyAndValues = append([]interface{}{ZapField("error", err)}, keyAndValues...)
}
p.log(ErrorLevel, msg, nil, keyAndValues)
}
// Debug uses fmt.Sprint to construct and log a message.
func (p *packZap) Debug(args ...interface{}) {
p.log(DebugLevel, "", args, nil)
}
// Info uses fmt.Sprint to construct and log a message.
func (p *packZap) Info(args ...interface{}) {
p.log(InfoLevel, "", args, nil)
}
// Warn uses fmt.Sprint to construct and log a message.
func (p *packZap) Warn(args ...interface{}) {
p.log(WarnLevel, "", args, nil)
}
// Error uses fmt.Sprint to construct and log a message.
func (p *packZap) Error(args ...interface{}) {
p.log(ErrorLevel, "", args, nil)
}
// DPanic uses fmt.Sprint to construct and log a message. In development, the
// logger then panics. (See DPanicLevel for details.)
func (p *packZap) DPanic(args ...interface{}) {
p.log(DPanicLevel, "", args, nil)
}
// Panic uses fmt.Sprint to construct and log a message, then panicl.
func (p *packZap) Panic(args ...interface{}) {
p.log(PanicLevel, "", args, nil)
}
// Fatal uses fmt.Sprint to construct and log a message, then calls ol.Exit.
func (p *packZap) Fatal(args ...interface{}) {
p.log(FatalLevel, "", args, nil)
}
// Debugf uses fmt.Sprintf to log a templated message.
func (p *packZap) Debugf(template string, args ...interface{}) {
p.log(DebugLevel, template, args, nil)
}
// Infof uses fmt.Sprintf to log a templated message.
func (p *packZap) Infof(template string, args ...interface{}) {
p.log(InfoLevel, template, args, nil)
}
// Warnf uses fmt.Sprintf to log a templated message.
func (p *packZap) Warnf(template string, args ...interface{}) {
p.log(WarnLevel, template, args, nil)
}
// Errorf uses fmt.Sprintf to log a templated message.
func (p *packZap) Errorf(template string, args ...interface{}) {
p.log(ErrorLevel, template, args, nil)
}
// DPanicf uses fmt.Sprintf to log a templated message. In development, the
// logger then panics. (See DPanicLevel for details.)
func (p *packZap) DPanicf(template string, args ...interface{}) {
p.log(DPanicLevel, template, args, nil)
}
// Panicf uses fmt.Sprintf to log a templated message, then panicl.
func (p *packZap) Panicf(template string, args ...interface{}) {
p.log(PanicLevel, template, args, nil)
}
// Fatalf uses fmt.Sprintf to log a templated message, then calls ol.Exit.
func (p *packZap) Fatalf(template string, args ...interface{}) {
p.log(FatalLevel, template, args, nil)
}
// Debugw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
//
// When debug-level logging is disabled, this is much faster than
// l.With(keysAndValues).Debug(msg)
func (p *packZap) Debugw(msg string, keysAndValues ...interface{}) {
p.log(DebugLevel, msg, nil, keysAndValues)
}
// Infow logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func (p *packZap) Infow(msg string, keysAndValues ...interface{}) {
p.log(InfoLevel, msg, nil, keysAndValues)
}
// Warnw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func (p *packZap) Warnw(msg string, keysAndValues ...interface{}) {
p.log(WarnLevel, msg, nil, keysAndValues)
}
// Errorw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func (p *packZap) Errorw(msg string, keysAndValues ...interface{}) {
p.log(ErrorLevel, msg, nil, keysAndValues)
}
// DPanicw logs a message with some additional context. In development, the
// logger then panics. (See DPanicLevel for details.) The variadic key-value
// pairs are treated as they are in With.
func (p *packZap) DPanicw(msg string, keysAndValues ...interface{}) {
p.log(DPanicLevel, msg, nil, keysAndValues)
}
// Panicw logs a message with some additional context, then panicl. The
// variadic key-value pairs are treated as they are in With.
func (p *packZap) Panicw(msg string, keysAndValues ...interface{}) {
p.log(PanicLevel, msg, nil, keysAndValues)
}
// Fatalw logs a message with some additional context, then calls ol.Exit. The
// variadic key-value pairs are treated as they are in With.
func (p *packZap) Fatalw(msg string, keysAndValues ...interface{}) {
p.log(FatalLevel, msg, nil, keysAndValues)
}
// Sync flushes any buffered log entries.
func (p *packZap) Sync() error {
return p.l.Sync()
}