/
logger.go
511 lines (424 loc) · 14.6 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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*
Copyright 2017 The Nuclio Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nucliozap
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/logrusorgru/aurora/v4"
"github.com/nuclio/logger"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type VarGroupMode string
const (
VarGroupModeFlattened VarGroupMode = "flattened"
VarGroupModeStructured VarGroupMode = "structured"
)
const DefaultVarGroupMode = VarGroupModeFlattened
type EncoderConfigJSON struct {
LineEnding string
VarGroupName string
VarGroupMode VarGroupMode
TimeFieldName string
TimeFieldEncoding string
ReflectedEncoder func(writer io.Writer) zapcore.ReflectedEncoder
}
type EncoderConfigConsole struct {
}
type EncoderConfig struct {
JSON EncoderConfigJSON
Console EncoderConfigConsole
}
func NewEncoderConfig() *EncoderConfig {
return &EncoderConfig{
JSON: EncoderConfigJSON{
LineEnding: ",",
TimeFieldName: "time",
TimeFieldEncoding: "epoch-millis",
VarGroupMode: DefaultVarGroupMode,
ReflectedEncoder: nil,
},
}
}
// Level is logging levels
type Level int8
// Predefined logging levels
const (
DebugLevel Level = Level(zapcore.DebugLevel)
InfoLevel Level = Level(zapcore.InfoLevel)
WarnLevel Level = Level(zapcore.WarnLevel)
ErrorLevel Level = Level(zapcore.ErrorLevel)
DPanicLevel Level = Level(zapcore.DPanicLevel)
PanicLevel Level = Level(zapcore.PanicLevel)
FatalLevel Level = Level(zapcore.FatalLevel)
)
// NuclioZap is a concrete implementation of the nuclio logger interface, using zap
type NuclioZap struct {
*zap.SugaredLogger
atomicLevel zap.AtomicLevel
outputWriter io.Writer
errorOutputWriter io.Writer
coloredLevelDebug string
coloredLevelInfo string
coloredLevelWarn string
coloredLevelError string
colorLoggerName aurora.Color
customEncoderConfig *EncoderConfig
encoding string
prepareVarsCallback func(vars []interface{}) interface{}
}
// NewNuclioZap create a configurable logger
func NewNuclioZap(name string,
encoding string,
customEncoderConfig *EncoderConfig,
sink io.Writer,
errSink io.Writer,
level Level) (*NuclioZap, error) {
if customEncoderConfig == nil {
customEncoderConfig = NewEncoderConfig()
}
newNuclioZap := &NuclioZap{
atomicLevel: zap.NewAtomicLevelAt(zapcore.Level(level)),
customEncoderConfig: customEncoderConfig,
encoding: encoding,
outputWriter: sink,
errorOutputWriter: errSink,
}
// create an encoder configuration
encoderConfig := newNuclioZap.getEncoderConfig(encoding, customEncoderConfig)
var encoder zapcore.Encoder
switch encoding {
case "json":
encoder = zapcore.NewJSONEncoder(*encoderConfig)
case "console":
encoder = zapcore.NewConsoleEncoder(*encoderConfig)
default:
return nil, fmt.Errorf("unknown encoding: %s", encoding)
}
opts := []zap.Option{
zap.ErrorOutput(zapcore.AddSync(newNuclioZap.errorOutputWriter)),
zap.Development(),
}
zlogger := zapcore.NewCore(encoder,
zapcore.AddSync(newNuclioZap.outputWriter),
newNuclioZap.atomicLevel,
)
newNuclioZap.SugaredLogger = zap.New(zlogger, opts...).Sugar().Named(name)
// initialize coloring by level
newNuclioZap.initializeColors()
switch customEncoderConfig.JSON.VarGroupMode {
case VarGroupModeStructured:
newNuclioZap.prepareVarsCallback = newNuclioZap.prepareVarsStructured
default:
newNuclioZap.prepareVarsCallback = newNuclioZap.prepareVarsFlattened
}
return newNuclioZap, nil
}
// We use this instead of testing.Verbose since we don't want to get testing flags in our code
func isVerboseTesting() bool {
for _, arg := range os.Args {
if arg == "-test.v=true" || arg == "-test.v" {
return true
}
}
return false
}
// NewNuclioZapTest creates a logger pre-configured for tests
func NewNuclioZapTest(name string) (*NuclioZap, error) {
var loggerLevel Level
if isVerboseTesting() {
loggerLevel = DebugLevel
} else {
loggerLevel = InfoLevel
}
loggerRedactor := NewRedactor(os.Stdout)
loggerRedactor.Disable()
return NewNuclioZapCmd(name, loggerLevel, loggerRedactor)
}
// NewNuclioZapCmd creates a logger pre-configured for commands
func NewNuclioZapCmd(name string, level Level, writer io.Writer) (*NuclioZap, error) {
return NewNuclioZap(name, "console", nil, writer, writer, level)
}
// GetLevelByName return logging level by name
func GetLevelByName(levelName string) Level {
switch levelName {
case "info":
return Level(zapcore.InfoLevel)
case "warn":
return Level(zapcore.WarnLevel)
case "error":
return Level(zapcore.ErrorLevel)
case "dpanic":
return Level(zapcore.DPanicLevel)
case "panic":
return Level(zapcore.PanicLevel)
case "fatal":
return Level(zapcore.FatalLevel)
default:
return Level(zapcore.DebugLevel)
}
}
func (nz *NuclioZap) GetRedactor() *Redactor {
redactor, ok := nz.outputWriter.(*Redactor)
if ok {
return redactor
}
return nil
}
// SetLevel sets the logging level
func (nz *NuclioZap) SetLevel(level Level) {
nz.atomicLevel.SetLevel(zapcore.Level(level))
}
// GetLevel returns the current logging level
func (nz *NuclioZap) GetLevel() Level {
return Level(nz.atomicLevel.Level())
}
// Errors emits error level log
func (nz *NuclioZap) Error(format interface{}, vars ...interface{}) {
formatString, formatIsString := format.(string)
if formatIsString {
nz.SugaredLogger.Errorf(formatString, vars...)
} else {
nz.SugaredLogger.Error(format)
}
}
// ErrorCtx emits an unstructured debug log with context
func (nz *NuclioZap) ErrorCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Errorw(nz.getFormatWithContext(ctx, format), nz.prepareVars(vars)...)
}
// ErrorWith emits error level log with arguments
func (nz *NuclioZap) ErrorWith(format interface{}, vars ...interface{}) {
nz.SugaredLogger.Errorw(format.(string), nz.prepareVars(vars)...)
}
// ErrorWithCtx emits debug level log with arguments
func (nz *NuclioZap) ErrorWithCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Errorw(format.(string), nz.addContextToVars(ctx, nz.prepareVars(vars))...)
}
// Warn emits warn level log
func (nz *NuclioZap) Warn(format interface{}, vars ...interface{}) {
formatString, formatIsString := format.(string)
if formatIsString {
nz.SugaredLogger.Warnf(formatString, vars...)
} else {
nz.SugaredLogger.Warn(format)
}
}
// WarnCtx emits an unstructured debug log with context
func (nz *NuclioZap) WarnCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Warnw(nz.getFormatWithContext(ctx, format), nz.prepareVars(vars)...)
}
// WarnWith emits warn level log with arguments
func (nz *NuclioZap) WarnWith(format interface{}, vars ...interface{}) {
nz.SugaredLogger.Warnw(format.(string), nz.prepareVars(vars)...)
}
// WarnWithCtx emits debug level log with arguments
func (nz *NuclioZap) WarnWithCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Warnw(format.(string), nz.addContextToVars(ctx, nz.prepareVars(vars))...)
}
// Info emits info level log
func (nz *NuclioZap) Info(format interface{}, vars ...interface{}) {
formatString, formatIsString := format.(string)
if formatIsString {
nz.SugaredLogger.Infof(formatString, vars...)
} else {
nz.SugaredLogger.Info(format)
}
}
// InfoCtx emits an unstructured debug log with context
func (nz *NuclioZap) InfoCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Infow(nz.getFormatWithContext(ctx, format), nz.prepareVars(vars)...)
}
// InfoWith emits info level log with arguments
func (nz *NuclioZap) InfoWith(format interface{}, vars ...interface{}) {
nz.SugaredLogger.Infow(format.(string), nz.prepareVars(vars)...)
}
// InfoWithCtx emits debug level log with arguments
func (nz *NuclioZap) InfoWithCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Infow(format.(string), nz.addContextToVars(ctx, nz.prepareVars(vars))...)
}
// Debug emits debug level log
func (nz *NuclioZap) Debug(format interface{}, vars ...interface{}) {
formatString, formatIsString := format.(string)
if formatIsString {
nz.SugaredLogger.Debugf(formatString, vars...)
} else {
nz.SugaredLogger.Debug(format)
}
}
// DebugCtx emits an unstructured debug log with context
func (nz *NuclioZap) DebugCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Debugw(nz.getFormatWithContext(ctx, format), nz.prepareVars(vars)...)
}
// DebugWith emits debug level log with arguments
func (nz *NuclioZap) DebugWith(format interface{}, vars ...interface{}) {
nz.SugaredLogger.Debugw(format.(string), nz.prepareVars(vars)...)
}
// DebugWithCtx emits debug level log with arguments
func (nz *NuclioZap) DebugWithCtx(ctx context.Context, format interface{}, vars ...interface{}) {
nz.SugaredLogger.Debugw(format.(string), nz.addContextToVars(ctx, nz.prepareVars(vars))...)
}
// Flush flushes the log
func (nz *NuclioZap) Flush() {
nz.Sync() // nolint: errcheck
}
// GetChild returned a named child logger
func (nz *NuclioZap) GetChild(name string) logger.Logger {
return &NuclioZap{
SugaredLogger: nz.Named(name),
encoding: nz.encoding,
customEncoderConfig: nz.customEncoderConfig,
prepareVarsCallback: nz.prepareVarsCallback,
}
}
func (nz *NuclioZap) encodeLoggerName(loggerName string, enc zapcore.PrimitiveArrayEncoder) {
const maxLoggerNameLength = 25
actualLoggerNameLength := len(loggerName)
var encodedLoggerName string
if actualLoggerNameLength >= maxLoggerNameLength {
encodedLoggerName = loggerName[actualLoggerNameLength-maxLoggerNameLength:]
} else {
encodedLoggerName = strings.Repeat(" ", maxLoggerNameLength-actualLoggerNameLength) + loggerName
}
// just truncate
enc.AppendString(aurora.Colorize(encodedLoggerName, nz.colorLoggerName).String())
}
func (nz *NuclioZap) encodeStdoutLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
switch level {
case zapcore.InfoLevel:
enc.AppendString(nz.coloredLevelInfo)
return
case zapcore.WarnLevel:
enc.AppendString(nz.coloredLevelWarn)
return
case zapcore.ErrorLevel:
enc.AppendString(nz.coloredLevelError)
return
}
enc.AppendString(nz.coloredLevelDebug)
}
func (nz *NuclioZap) encodeStdoutTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("06.01.02 15:04:05.000"))
}
func (nz *NuclioZap) initializeColors() {
nz.coloredLevelDebug = aurora.Green("(D)").String()
nz.coloredLevelInfo = aurora.Blue("(I)").String()
nz.coloredLevelWarn = aurora.Yellow("(W)").String()
nz.coloredLevelError = aurora.Red("(E)").String()
nz.colorLoggerName = aurora.WhiteFg
}
func (nz *NuclioZap) getEncoderConfig(encoding string, encoderConfig *EncoderConfig) *zapcore.EncoderConfig {
if encoding == "console" {
return &zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "name",
CallerKey: "",
MessageKey: "message",
StacktraceKey: "stack",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: nz.encodeStdoutLevel,
EncodeTime: nz.encodeStdoutTime,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: func(zapcore.EntryCaller, zapcore.PrimitiveArrayEncoder) {},
EncodeName: nz.encodeLoggerName,
ConsoleSeparator: " ",
}
}
var timeEncoder zapcore.TimeEncoder
switch encoderConfig.JSON.TimeFieldEncoding {
case "iso8601":
timeEncoder = zapcore.ISO8601TimeEncoder
default:
timeEncoder = zapcore.EpochMillisTimeEncoder
}
return &zapcore.EncoderConfig{
TimeKey: encoderConfig.JSON.TimeFieldName,
NameKey: "name",
LevelKey: "level",
CallerKey: "",
MessageKey: "message",
StacktraceKey: "stack",
LineEnding: encoderConfig.JSON.LineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: timeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: func(zapcore.EntryCaller, zapcore.PrimitiveArrayEncoder) {},
EncodeName: zapcore.FullNameEncoder,
NewReflectedEncoder: encoderConfig.JSON.ReflectedEncoder,
}
}
func (nz *NuclioZap) addContextToVars(ctx context.Context, vars []interface{}) []interface{} {
if ctx == nil {
return vars
}
// get request ID from context
requestID := ctx.Value("RequestID")
// if not set, don't add it to vars
if requestID == nil || requestID == "" {
return vars
}
// create a slice 2 slots larger
varsWithContext := make([]interface{}, 0, len(vars)+2)
varsWithContext = append(varsWithContext, "requestID")
varsWithContext = append(varsWithContext, requestID)
varsWithContext = append(varsWithContext, vars...)
return varsWithContext
}
func (nz *NuclioZap) getFormatWithContext(ctx context.Context, format interface{}) string {
formatString := format.(string)
// get request ID from context
requestID := ctx.Value("RequestID")
// if not set, don't add it to vars
if requestID == nil || requestID == "" {
return formatString
}
return formatString + fmt.Sprintf(" (requestID: %s)", requestID)
}
func (nz *NuclioZap) prepareVars(vars []interface{}) []interface{} {
if nz.encoding != "json" || nz.customEncoderConfig == nil || nz.customEncoderConfig.JSON.VarGroupName == "" {
return vars
}
if len(vars) == 0 {
// if nothing was created, don't generate a group
return []interface{}{}
}
// must be an even number of parameters
if len(vars)&0x1 != 0 {
panic("Odd number of logging vars - must be key/value")
}
return []interface{}{
nz.customEncoderConfig.JSON.VarGroupName,
nz.prepareVarsCallback(vars),
}
}
func (nz *NuclioZap) prepareVarsStructured(vars []interface{}) interface{} {
formattedVars := map[string]interface{}{}
// create key, value pairs
for varIndex := 0; varIndex < len(vars); varIndex += 2 {
formattedVars[fmt.Sprintf("%s", vars[varIndex])] = vars[varIndex+1]
}
return formattedVars
}
func (nz *NuclioZap) prepareVarsFlattened(vars []interface{}) interface{} {
var s strings.Builder
delimiter := " || "
// create key=value pairs
for varIndex := 0; varIndex < len(vars); varIndex += 2 {
s.WriteString(fmt.Sprintf("%s=%+v%s", vars[varIndex], vars[varIndex+1], delimiter))
}
return s.String()[:s.Len()-len(delimiter)]
}