This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.go
554 lines (467 loc) · 14.4 KB
/
base.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package gomol
import (
"os"
"sync/atomic"
"time"
"github.com/efritz/glock"
)
type baseConfigFunc func(b *Base)
func withClock(clock glock.Clock) baseConfigFunc {
return func(b *Base) {
b.clock = clock
}
}
/*
Base holds an instance of all information needed for logging. It is possible
to create multiple instances of Base if multiple sets of loggers or attributes
are desired.
*/
type Base struct {
// This must be at the beginning of the struct due to
// how 64 bit atomic values are handled on 32 bit systems
// in Go.
sequence uint64
clock glock.Clock
isInitialized bool
config *Config
errorChan chan<- error
queue *queue
logLevel LogLevel
BaseAttrs *Attrs
loggers []Logger
fallbackLogger Logger
hookPreQueue []HookPreQueue
}
// NewBase creates a new instance of Base with default values set.
func NewBase(configs ...baseConfigFunc) *Base {
b := &Base{
clock: glock.NewRealClock(),
config: NewConfig(),
logLevel: LevelDebug,
sequence: 0,
BaseAttrs: NewAttrs(),
loggers: make([]Logger, 0),
hookPreQueue: make([]HookPreQueue, 0),
}
for _, f := range configs {
f(b)
}
return b
}
type appExiter interface {
Exit(code int)
}
type osExiter struct{}
func (exiter *osExiter) Exit(code int) {
os.Exit(code)
}
var curExiter appExiter = &osExiter{}
func setExiter(exiter appExiter) {
curExiter = exiter
}
// SetConfig will set the configuration for the Base to the given Config
func (b *Base) SetConfig(config *Config) {
b.config = config
}
// SetErrorChan will register a channel as the consumer of internal error
// events. This channel will be closed once ShutdownLoggers has finished.
// The consumer of this channel is expected to be efficient as writing to
// this channel will block.
func (b *Base) SetErrorChan(ch chan<- error) {
b.errorChan = ch
}
func (b *Base) report(err error) {
if b.errorChan != nil {
b.errorChan <- err
}
}
/*
SetLogLevel sets the level messages will be logged at. It will log any message
that is at the level or more severe than the level.
*/
func (b *Base) SetLogLevel(level LogLevel) {
b.logLevel = level
}
func (b *Base) shouldLog(level LogLevel) bool {
if level <= b.logLevel {
return true
}
return false
}
// SetFallbackLogger sets a Logger to be used if there aren't any loggers added or any of
// the added loggers are in a degraded or unhealthy state. A Logger passed to SetFallbackLogger
// will be initialized if it hasn't been already. In addition, if the Logger fails to initialize
// completely the fallback logger will fail to be set.
func (b *Base) SetFallbackLogger(logger Logger) error {
if logger == nil {
if b.fallbackLogger != nil && b.fallbackLogger.IsInitialized() {
b.fallbackLogger.ShutdownLogger()
}
b.fallbackLogger = nil
return nil
}
if !logger.IsInitialized() {
err := logger.InitLogger()
if err != nil {
return err
}
}
// Shut down any old logger we might already have a reference to
if b.fallbackLogger != nil && b.fallbackLogger.IsInitialized() {
b.fallbackLogger.ShutdownLogger()
}
b.fallbackLogger = logger
return nil
}
// AddLogger adds a new logger instance to the Base
func (b *Base) AddLogger(logger Logger) error {
if b.IsInitialized() && !logger.IsInitialized() {
err := logger.InitLogger()
if err != nil {
return err
}
} else if !b.IsInitialized() && logger.IsInitialized() {
err := logger.ShutdownLogger()
if err != nil {
return err
}
}
b.loggers = append(b.loggers, logger)
if hook, ok := logger.(HookPreQueue); ok {
b.hookPreQueue = append(b.hookPreQueue, hook)
}
logger.SetBase(b)
return nil
}
/*
RemoveLogger will run ShutdownLogger on the given logger and then remove the given
Logger from the list in Base
*/
func (b *Base) RemoveLogger(logger Logger) error {
for idx, rLogger := range b.loggers {
if rLogger == logger {
err := rLogger.ShutdownLogger()
if err != nil {
return err
}
b.loggers[idx] = b.loggers[len(b.loggers)-1]
b.loggers[len(b.loggers)-1] = nil
b.loggers = b.loggers[:len(b.loggers)-1]
return nil
}
}
// Remove any hook instances the logger has
for idx, hookLogger := range b.hookPreQueue {
if hookLogger == logger {
b.hookPreQueue[idx] = b.hookPreQueue[len(b.hookPreQueue)-1]
b.hookPreQueue[len(b.hookPreQueue)-1] = nil
b.hookPreQueue = b.hookPreQueue[:len(b.hookPreQueue)-1]
}
}
return nil
}
/*
ClearLoggers will shut down and remove any loggers added to the Base. If an
error occurs while shutting down one of the loggers, the list will not be
cleared but any loggers that have already been shut down before the error
occurred will remain shut down.
*/
func (b *Base) ClearLoggers() error {
for _, logger := range b.loggers {
err := logger.ShutdownLogger()
if err != nil {
return err
}
}
b.loggers = make([]Logger, 0)
b.hookPreQueue = make([]HookPreQueue, 0)
return nil
}
// IsInitialized returns true if InitLoggers has been successfully run on the Base
func (b *Base) IsInitialized() bool {
return b.isInitialized
}
/*
InitLoggers will run InitLogger on each Logger that has been added to the Base.
If an error occurs in initializing a logger, the loggers that have already been
initialized will continue to be initialized.
*/
func (b *Base) InitLoggers() error {
if b.queue == nil {
b.queue = newQueue(b, b.config.MaxQueueSize)
}
for _, logger := range b.loggers {
err := logger.InitLogger()
if err != nil {
return err
}
}
b.queue.startWorker()
b.isInitialized = true
return nil
}
// Flush will wait until all messages currently queued are distributed to
// all initialized loggers
func (b *Base) Flush() {
if b.queue != nil {
b.queue.flush()
}
}
/*
ShutdownLoggers will run ShutdownLogger on each Logger in Base. If an error occurs
while shutting down a Logger, the error will be returned and all the loggers that
were already shut down will remain shut down.
*/
func (b *Base) ShutdownLoggers() error {
// Before shutting down we should flush all the messsages
b.Flush()
for _, logger := range b.loggers {
err := logger.ShutdownLogger()
if err != nil {
return err
}
}
if b.queue != nil {
b.queue.stopWorker()
b.queue = nil
}
if b.errorChan != nil {
close(b.errorChan)
b.errorChan = nil
}
b.isInitialized = false
return nil
}
/*
NewLogAdapter creates a LogAdapter using Base to log messages
*/
func (b *Base) NewLogAdapter(attrs *Attrs) *LogAdapter {
return NewLogAdapterFor(b, attrs)
}
// ClearAttrs will remove all the attributes added to Base
func (b *Base) ClearAttrs() {
b.BaseAttrs = NewAttrs()
}
/*
SetAttr will set the value for the attribute with the name key. If the key
already exists it will be overwritten with the new value.
*/
func (b *Base) SetAttr(key string, value interface{}) {
b.BaseAttrs.SetAttr(key, value)
}
/*
GetAttr will return the current value for the given attribute key. If the key
isn't set this will return nil
*/
func (b *Base) GetAttr(key string) interface{} {
return b.BaseAttrs.GetAttr(key)
}
// RemoveAttr will remove the attribute with the name key.
func (b *Base) RemoveAttr(key string) {
b.BaseAttrs.RemoveAttr(key)
}
// LogWithTime will log a message at the provided level to all added loggers with the timestamp set to the
// value of ts.
func (b *Base) LogWithTime(level LogLevel, ts time.Time, m *Attrs, msg string, a ...interface{}) error {
if !b.shouldLog(level) {
return nil
}
if !b.isInitialized {
return ErrNotInitialized
}
if len(b.config.FilenameAttr) > 0 || len(b.config.LineNumberAttr) > 0 {
file, line := getCallerInfo()
if m == nil {
m = NewAttrs()
}
if len(b.config.FilenameAttr) > 0 {
m.SetAttr(b.config.FilenameAttr, file)
}
if len(b.config.LineNumberAttr) > 0 {
m.SetAttr(b.config.LineNumberAttr, line)
}
}
if len(b.config.SequenceAttr) > 0 {
if m == nil {
m = NewAttrs()
}
seq := atomic.AddUint64(&b.sequence, 1)
m.SetAttr(b.config.SequenceAttr, seq)
}
nm := newMessage(ts, b, level, m, msg, a...)
for _, hook := range b.hookPreQueue {
err := hook.PreQueue(nm)
if err != nil {
return err
}
}
return b.queue.queueMessage(nm)
}
// Log will log a message at the provided level to all added loggers with the timestamp set to the time
// Log was called.
func (b *Base) Log(level LogLevel, m *Attrs, msg string, a ...interface{}) error {
return b.LogWithTime(level, b.clock.Now(), m, msg, a...)
}
// Dbg is a short-hand version of Debug
func (b *Base) Dbg(msg string) error {
return b.Debug(msg)
}
// Dbgf is a short-hand version of Debugf
func (b *Base) Dbgf(msg string, a ...interface{}) error {
return b.Debugf(msg, a...)
}
// Dbgm is a short-hand version of Debugm
func (b *Base) Dbgm(m *Attrs, msg string, a ...interface{}) error {
return b.Debugm(m, msg, a...)
}
// Debug logs msg to all added loggers at LogLevel.LevelDebug
func (b *Base) Debug(msg string) error {
return b.Log(LevelDebug, nil, msg)
}
/*
Debugf uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelDebug
*/
func (b *Base) Debugf(msg string, a ...interface{}) error {
return b.Log(LevelDebug, nil, msg, a...)
}
/*
Debugm uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelDebug. It will also
merge all attributes passed in m with any attributes added to Base and include them
with the message if the Logger supports it.
*/
func (b *Base) Debugm(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelDebug, m, msg, a...)
}
// Info logs msg to all added loggers at LogLevel.LevelInfo
func (b *Base) Info(msg string) error {
return b.Log(LevelInfo, nil, msg)
}
/*
Infof uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelInfo
*/
func (b *Base) Infof(msg string, a ...interface{}) error {
return b.Log(LevelInfo, nil, msg, a...)
}
/*
Infom uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelInfo. It will also
merge all attributes passed in m with any attributes added to Base and include them
with the message if the Logger supports it.
*/
func (b *Base) Infom(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelInfo, m, msg, a...)
}
// Warn is a short-hand version of Warning
func (b *Base) Warn(msg string) error {
return b.Warning(msg)
}
// Warnf is a short-hand version of Warningf
func (b *Base) Warnf(msg string, a ...interface{}) error {
return b.Warningf(msg, a...)
}
// Warnm is a short-hand version of Warningm
func (b *Base) Warnm(m *Attrs, msg string, a ...interface{}) error {
return b.Warningm(m, msg, a...)
}
/*
Warning uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelWarning
*/
func (b *Base) Warning(msg string) error {
return b.Log(LevelWarning, nil, msg)
}
/*
Warningf uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelWarning
*/
func (b *Base) Warningf(msg string, a ...interface{}) error {
return b.Log(LevelWarning, nil, msg, a...)
}
/*
Warningm uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelWarning. It will also
merge all attributes passed in m with any attributes added to Base and include them
with the message if the Logger supports it.
*/
func (b *Base) Warningm(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelWarning, m, msg, a...)
}
// Err is a short-hand version of Error
func (b *Base) Err(msg string) error {
return b.Error(msg)
}
// Errf is a short-hand version of Errorf
func (b *Base) Errf(msg string, a ...interface{}) error {
return b.Errorf(msg, a...)
}
// Errm is a short-hand version of Errorm
func (b *Base) Errm(m *Attrs, msg string, a ...interface{}) error {
return b.Errorm(m, msg, a...)
}
/*
Error uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelError
*/
func (b *Base) Error(msg string) error {
return b.Log(LevelError, nil, msg)
}
/*
Errorf uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelError
*/
func (b *Base) Errorf(msg string, a ...interface{}) error {
return b.Log(LevelError, nil, msg, a...)
}
/*
Errorm uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelError. It will also
merge all attributes passed in m with any attributes added to Base and include them
with the message if the Logger supports it.
*/
func (b *Base) Errorm(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelError, m, msg, a...)
}
/*
Fatal uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelFatal
*/
func (b *Base) Fatal(msg string) error {
return b.Log(LevelFatal, nil, msg)
}
/*
Fatalf uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelFatal
*/
func (b *Base) Fatalf(msg string, a ...interface{}) error {
return b.Log(LevelFatal, nil, msg, a...)
}
/*
Fatalm uses msg as a format string with subsequent parameters as values and logs
the resulting message to all added loggers at LogLevel.LevelFatal. It will also
merge all attributes passed in m with any attributes added to Base and include them
with the message if the Logger supports it.
*/
func (b *Base) Fatalm(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelFatal, m, msg, a...)
}
// Die will log a message using Fatal, call ShutdownLoggers and then exit the application with the provided exit code.
func (b *Base) Die(exitCode int, msg string) {
b.Log(LevelFatal, nil, msg)
b.ShutdownLoggers()
curExiter.Exit(exitCode)
}
// Dief will log a message using Fatalf, call ShutdownLoggers and then exit the application with the provided exit code.
func (b *Base) Dief(exitCode int, msg string, a ...interface{}) {
b.Log(LevelFatal, nil, msg, a...)
b.ShutdownLoggers()
curExiter.Exit(exitCode)
}
// Diem will log a message using Fatalm, call ShutdownLoggers and then exit the application with the provided exit code.
func (b *Base) Diem(exitCode int, m *Attrs, msg string, a ...interface{}) {
b.Log(LevelFatal, m, msg, a...)
b.ShutdownLoggers()
curExiter.Exit(exitCode)
}