-
Notifications
You must be signed in to change notification settings - Fork 110
/
impl.go
468 lines (390 loc) · 12.9 KB
/
impl.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
package logging
import (
"context"
"errors"
"fmt"
"os"
"runtime"
"testing"
"time"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest"
)
type (
impl struct {
name string
level AtomicLevel
appenders []Appender
// Logging to a `testing.T` always includes a filename/line number. We use this helper to
// avoid that. This function is a no-op for non-test loggers. See `NewTestAppender`
// documentation for more details.
testHelper func()
}
// LogEntry embeds a zapcore Entry and slice of Fields.
LogEntry struct {
zapcore.Entry
fields []zapcore.Field
}
)
func (imp *impl) NewLogEntry() *LogEntry {
ret := &LogEntry{}
ret.Time = time.Now()
ret.LoggerName = imp.name
ret.Caller = getCaller()
return ret
}
func (imp *impl) AddAppender(appender Appender) {
imp.appenders = append(imp.appenders, appender)
}
func (imp *impl) Desugar() *zap.Logger {
return imp.AsZap().Desugar()
}
func (imp *impl) SetLevel(level Level) {
imp.level.Set(level)
}
func (imp *impl) GetLevel() Level {
return imp.level.Get()
}
func (imp *impl) Level() zapcore.Level {
return imp.GetLevel().AsZap()
}
func (imp *impl) Sublogger(subname string) Logger {
newName := subname
if imp.name != "" {
newName = fmt.Sprintf("%s.%s", imp.name, subname)
}
// Force all parameters to be passed. Avoid bugs where adding members to `impl` silently
// succeeds without a change here.
return &impl{
newName,
NewAtomicLevelAt(imp.level.Get()),
imp.appenders,
imp.testHelper,
}
}
func (imp *impl) Named(name string) *zap.SugaredLogger {
return imp.AsZap().Named(name)
}
func (imp *impl) Sync() error {
var errs []error
for _, appender := range imp.appenders {
if err := appender.Sync(); err != nil {
errs = append(errs, err)
}
}
return multierr.Combine(errs...)
}
func (imp *impl) With(args ...interface{}) *zap.SugaredLogger {
return imp.AsZap().With(args...)
}
func (imp *impl) WithOptions(opts ...zap.Option) *zap.SugaredLogger {
return imp.AsZap().WithOptions(opts...)
}
func (imp *impl) AsZap() *zap.SugaredLogger {
// When downconverting to a SugaredLogger, copy those that implement the `zapcore.Core`
// interface. This includes the net logger for viam servers and the observed logs for tests.
var copiedCores []zapcore.Core
// When we find a `testAppender`, copy the underlying `testing.TB` object and construct a
// `zaptest.NewLogger` from it.
var testingObj testing.TB
for _, appender := range imp.appenders {
if core, ok := appender.(zapcore.Core); ok {
copiedCores = append(copiedCores, core)
}
if testAppender, ok := appender.(*testAppender); ok {
testingObj = testAppender.tb
}
}
var ret *zap.SugaredLogger
if testingObj == nil {
config := NewZapLoggerConfig()
// Use the global zap `AtomicLevel` such that the constructed zap logger can observe changes to
// the debug flag.
if imp.level.Get() == DEBUG {
config.Level = zap.NewAtomicLevelAt(zapcore.DebugLevel)
} else {
config.Level = GlobalLogLevel
}
ret = zap.Must(config.Build()).Sugar().Named(imp.name)
} else {
// `zaptest.NewLogger` always constructs a logger at the `zapcore.DebugLevel`.
ret = zaptest.NewLogger(testingObj, zaptest.WrapOptions(zap.AddCaller())).Sugar().Named(imp.name)
}
for _, core := range copiedCores {
ret = ret.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewTee(c, core)
}))
}
return ret
}
func (imp *impl) shouldLog(logLevel Level) bool {
if GlobalLogLevel.Level() == zapcore.DebugLevel {
return true
}
return logLevel >= imp.level.Get()
}
func (imp *impl) log(entry *LogEntry) {
imp.testHelper()
for _, appender := range imp.appenders {
err := appender.Write(entry.Entry, entry.fields)
if err != nil {
fmt.Fprint(os.Stderr, err)
}
}
}
// Constructs the log message by forwarding to `fmt.Sprint`. `traceKey` may be the empty string.
func (imp *impl) format(logLevel Level, traceKey string, args ...interface{}) *LogEntry {
logEntry := imp.NewLogEntry()
logEntry.Level = logLevel.AsZap()
logEntry.Message = fmt.Sprint(args...)
if traceKey != emptyTraceKey {
logEntry.fields = append(logEntry.fields, zap.String("traceKey", traceKey))
}
return logEntry
}
// Constructs the log message by forwarding to `fmt.Sprintf`. `traceKey` may be the empty string.
func (imp *impl) formatf(logLevel Level, traceKey, template string, args ...interface{}) *LogEntry {
logEntry := imp.NewLogEntry()
logEntry.Level = logLevel.AsZap()
logEntry.Message = fmt.Sprintf(template, args...)
if traceKey != emptyTraceKey {
logEntry.fields = append(logEntry.fields, zap.String("traceKey", traceKey))
}
return logEntry
}
// Turns `keysAndValues` into a map where the odd elements are the keys and their following even
// counterpart is the value. The keys are expected to be strings. The values are json
// serialized. Only public fields are included in the serialization. `traceKey` may be the empty
// string.
func (imp *impl) formatw(logLevel Level, traceKey, msg string, keysAndValues ...interface{}) *LogEntry {
logEntry := imp.NewLogEntry()
logEntry.Level = logLevel.AsZap()
logEntry.Message = msg
logEntry.fields = make([]zapcore.Field, 0, len(keysAndValues)/2+1)
if traceKey != emptyTraceKey {
logEntry.fields = append(logEntry.fields, zap.String("traceKey", traceKey))
}
for keyIdx := 0; keyIdx < len(keysAndValues); keyIdx += 2 {
keyObj := keysAndValues[keyIdx]
var keyStr string
if stringer, ok := keyObj.(fmt.Stringer); ok {
keyStr = stringer.String()
} else {
keyStr = fmt.Sprintf("%v", keyObj)
}
if keyIdx+1 < len(keysAndValues) {
logEntry.fields = append(logEntry.fields, zap.Any(keyStr, keysAndValues[keyIdx+1]))
} else {
// API mis-use. Rather than logging a logging mis-use, slip in an error message such
// that we don't silenlty discard it.
logEntry.fields = append(logEntry.fields, zap.Any(keyStr, errors.New("unpaired log key")))
}
}
return logEntry
}
func (imp *impl) Debug(args ...interface{}) {
imp.testHelper()
if imp.shouldLog(DEBUG) {
imp.log(imp.format(DEBUG, emptyTraceKey, args...))
}
}
func (imp *impl) CDebug(ctx context.Context, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for debug, or if there's a trace key.
if imp.shouldLog(DEBUG) || dbgName != emptyTraceKey {
imp.log(imp.format(DEBUG, dbgName, args...))
}
}
func (imp *impl) Debugf(template string, args ...interface{}) {
imp.testHelper()
if imp.shouldLog(DEBUG) {
imp.log(imp.formatf(DEBUG, emptyTraceKey, template, args...))
}
}
func (imp *impl) CDebugf(ctx context.Context, template string, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for debug, or if there's a trace key.
if imp.shouldLog(DEBUG) || dbgName != emptyTraceKey {
imp.log(imp.formatf(DEBUG, dbgName, template, args...))
}
}
func (imp *impl) Debugw(msg string, keysAndValues ...interface{}) {
imp.testHelper()
if imp.shouldLog(DEBUG) {
imp.log(imp.formatw(DEBUG, emptyTraceKey, msg, keysAndValues...))
}
}
func (imp *impl) CDebugw(ctx context.Context, msg string, keysAndValues ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for debug, or if there's a trace key.
if imp.shouldLog(DEBUG) || dbgName != emptyTraceKey {
imp.log(imp.formatw(DEBUG, dbgName, msg, keysAndValues...))
}
}
func (imp *impl) Info(args ...interface{}) {
imp.testHelper()
if imp.shouldLog(INFO) {
imp.log(imp.format(INFO, emptyTraceKey, args...))
}
}
func (imp *impl) CInfo(ctx context.Context, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for info, or if there's a trace key.
if imp.shouldLog(INFO) || dbgName != emptyTraceKey {
imp.log(imp.format(INFO, dbgName, args...))
}
}
func (imp *impl) Infof(template string, args ...interface{}) {
imp.testHelper()
if imp.shouldLog(INFO) {
imp.log(imp.formatf(INFO, emptyTraceKey, template, args...))
}
}
func (imp *impl) CInfof(ctx context.Context, template string, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for info, or if there's a trace key.
if imp.shouldLog(INFO) || dbgName != emptyTraceKey {
imp.log(imp.formatf(INFO, dbgName, template, args...))
}
}
func (imp *impl) Infow(msg string, keysAndValues ...interface{}) {
imp.testHelper()
if imp.shouldLog(INFO) {
imp.log(imp.formatw(INFO, emptyTraceKey, msg, keysAndValues...))
}
}
func (imp *impl) CInfow(ctx context.Context, msg string, keysAndValues ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for info, or if there's a trace key.
if imp.shouldLog(INFO) || dbgName != emptyTraceKey {
imp.log(imp.formatw(INFO, dbgName, msg, keysAndValues...))
}
}
func (imp *impl) Warn(args ...interface{}) {
imp.testHelper()
if imp.shouldLog(WARN) {
imp.log(imp.format(WARN, emptyTraceKey, args...))
}
}
func (imp *impl) CWarn(ctx context.Context, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for warn, or if there's a trace key.
if imp.shouldLog(WARN) || dbgName != emptyTraceKey {
imp.log(imp.format(WARN, dbgName, args...))
}
}
func (imp *impl) Warnf(template string, args ...interface{}) {
imp.testHelper()
if imp.shouldLog(WARN) {
imp.log(imp.formatf(WARN, emptyTraceKey, template, args...))
}
}
func (imp *impl) CWarnf(ctx context.Context, template string, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for warn, or if there's a trace key.
if imp.shouldLog(WARN) || dbgName != emptyTraceKey {
imp.log(imp.formatf(WARN, dbgName, template, args...))
}
}
func (imp *impl) Warnw(msg string, keysAndValues ...interface{}) {
imp.testHelper()
if imp.shouldLog(WARN) {
imp.log(imp.formatw(WARN, emptyTraceKey, msg, keysAndValues...))
}
}
func (imp *impl) CWarnw(ctx context.Context, msg string, keysAndValues ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for warn, or if there's a trace key.
if imp.shouldLog(WARN) || dbgName != emptyTraceKey {
imp.log(imp.formatw(WARN, dbgName, msg, keysAndValues...))
}
}
func (imp *impl) Error(args ...interface{}) {
imp.testHelper()
if imp.shouldLog(ERROR) {
imp.log(imp.format(ERROR, emptyTraceKey, args...))
}
}
func (imp *impl) CError(ctx context.Context, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for error, or if there's a trace key.
if imp.shouldLog(ERROR) || dbgName != emptyTraceKey {
imp.log(imp.format(ERROR, dbgName, args...))
}
}
func (imp *impl) Errorf(template string, args ...interface{}) {
imp.testHelper()
if imp.shouldLog(ERROR) {
imp.log(imp.formatf(ERROR, emptyTraceKey, template, args...))
}
}
func (imp *impl) CErrorf(ctx context.Context, template string, args ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for error, or if there's a trace key.
if imp.shouldLog(ERROR) || dbgName != emptyTraceKey {
imp.log(imp.formatf(ERROR, dbgName, template, args...))
}
}
func (imp *impl) Errorw(msg string, keysAndValues ...interface{}) {
imp.testHelper()
if imp.shouldLog(ERROR) {
imp.log(imp.formatw(ERROR, emptyTraceKey, msg, keysAndValues...))
}
}
func (imp *impl) CErrorw(ctx context.Context, msg string, keysAndValues ...interface{}) {
imp.testHelper()
dbgName := GetName(ctx)
// We log if the logger is configured for error, or if there's a trace key.
if imp.shouldLog(ERROR) || dbgName != emptyTraceKey {
imp.log(imp.formatw(ERROR, dbgName, msg, keysAndValues...))
}
}
// These Fatal* methods log as errors then exit the process.
func (imp *impl) Fatal(args ...interface{}) {
imp.testHelper()
imp.log(imp.format(ERROR, emptyTraceKey, args...))
os.Exit(1)
}
func (imp *impl) Fatalf(template string, args ...interface{}) {
imp.testHelper()
imp.log(imp.formatf(ERROR, emptyTraceKey, template, args...))
os.Exit(1)
}
func (imp *impl) Fatalw(msg string, keysAndValues ...interface{}) {
imp.testHelper()
imp.log(imp.formatw(ERROR, emptyTraceKey, msg, keysAndValues...))
os.Exit(1)
}
// Return example: "logging/impl_test.go:36". `entryCaller` is an outParameter.
func getCaller() zapcore.EntryCaller {
var ok bool
var entryCaller zapcore.EntryCaller
const framesToSkip = 4
entryCaller.PC, entryCaller.File, entryCaller.Line, ok = runtime.Caller(framesToSkip)
if !ok {
return entryCaller
}
entryCaller.Defined = true
// Getting an individual program counter and the file/line/function at that address can be
// nuanced due to inlining. The alternative is getting all program counters on the stack and
// iterating through the associated frames with `runtime.CallersFrames`. A note to future
// readers that this choice is due to less coding/convenience.
runtimeFunc := runtime.FuncForPC(entryCaller.PC)
if runtimeFunc != nil {
entryCaller.Function = runtimeFunc.Name()
}
return entryCaller
}