-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
564 lines (489 loc) · 15.9 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
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
555
556
557
558
559
560
561
562
563
564
package logiface
import (
"fmt"
"github.com/joeycumines/go-catrate"
"golang.org/x/exp/maps"
"os"
"sync"
"time"
)
type (
// Logger is the core logger implementation, and constitutes the core
// functionality, provided by this package.
Logger[E Event] struct {
// WARNING: Fields added must be initialized in both New and Logger.Logger
modifier Modifier[E]
shared *loggerShared[E]
}
// loggerShared models the shared state, common between a root Logger
// instance, and all it's child instances.
loggerShared[E Event] struct {
// WARNING: Fields added must be initialized in both New and Logger.Logger
factory EventFactory[E]
releaser EventReleaser[E]
writer Writer[E]
root *Logger[E]
pool *sync.Pool
json *jsonSupport[E]
catrate *catrate.Limiter
level Level
dpanic Level
}
// Option is a configuration option for constructing Logger instances,
// using the New function, or it's alias(es), e.g. LoggerFactory.New.
Option[E Event] interface {
apply(c *loggerConfig[E])
}
optionFunc[E Event] func(c *loggerConfig[E])
// loggerConfig is the internal configuration type used by the New function
loggerConfig[E Event] struct {
factory EventFactory[E]
releaser EventReleaser[E]
json *jsonSupport[E]
categoryRateLimits map[time.Duration]int
writer WriterSlice[E]
modifier ModifierSlice[E]
level Level
dpanic Level
}
// LoggerFactory provides aliases for package functions including New, as
// well as the functions returning Option values.
// This allows the Event type to be omitted from all but one location.
//
// See also L, an instance of LoggerFactory[Event]{}.
LoggerFactory[E Event] struct{}
)
var (
// L exposes New and it's Option functions (e.g. WithWriter) as
// methods, using the generic Event type.
//
// It's provided as a convenience.
L = LoggerFactory[Event]{}
// genericBuilderPool is a shared pool for the Builder[Event] type.
genericBuilderPool = sync.Pool{New: newBuilder[Event]}
)
//lint:ignore U1000 it is used
func (x optionFunc[E]) apply(c *loggerConfig[E]) { x(c) }
// WithOptions combines multiple Option values into one.
//
// See also LoggerFactory.WithOptions and L (an instance of LoggerFactory[Event]{}).
func WithOptions[E Event](options ...Option[E]) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
for _, option := range options {
option.apply(c)
}
})
}
// WithOptions is an alias of the package function of the same name.
func (LoggerFactory[E]) WithOptions(options ...Option[E]) Option[E] {
return WithOptions[E](options...)
}
// WithEventFactory configures the logger's EventFactory.
//
// See also LoggerFactory.WithEventFactory and L (an instance of LoggerFactory[Event]{}).
func WithEventFactory[E Event](factory EventFactory[E]) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.factory = factory
})
}
// WithEventFactory is an alias of the package function of the same name.
func (LoggerFactory[E]) WithEventFactory(factory EventFactory[E]) Option[E] {
return WithEventFactory[E](factory)
}
// WithEventReleaser configures the logger's EventReleaser.
//
// See also LoggerFactory.WithEventReleaser and L (an instance of LoggerFactory[Event]{}).
func WithEventReleaser[E Event](releaser EventReleaser[E]) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.releaser = releaser
})
}
// WithEventReleaser is an alias of the package function of the same name.
func (LoggerFactory[E]) WithEventReleaser(releaser EventReleaser[E]) Option[E] {
return WithEventReleaser[E](releaser)
}
// WithWriter configures the logger's [Writer], prepending it to an internal
// [WriterSlice].
//
// See also LoggerFactory.WithWriter and L (an instance of LoggerFactory[Event]{}).
func WithWriter[E Event](writer Writer[E]) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
// note: reversed on init
c.writer = append(c.writer, writer)
})
}
// WithWriter is an alias of the package function of the same name.
func (LoggerFactory[E]) WithWriter(writer Writer[E]) Option[E] {
return WithWriter[E](writer)
}
// WithModifier configures the logger's [Modifier], appending it to an internal
// [ModifierSlice].
//
// See also LoggerFactory.WithModifier and L (an instance of LoggerFactory[Event]{}).
func WithModifier[E Event](modifier Modifier[E]) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.modifier = append(c.modifier, modifier)
})
}
// WithModifier is an alias of the package function of the same name.
func (LoggerFactory[E]) WithModifier(modifier Modifier[E]) Option[E] {
return WithModifier[E](modifier)
}
// WithLevel configures the logger's Level.
//
// Level will be used to filter events that are mapped to a syslog-defined level.
// Events with a custom level will always be logged.
//
// See also LoggerFactory.WithLevel and L (an instance of LoggerFactory[Event]{}).
func WithLevel[E Event](level Level) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.level = level
})
}
// WithLevel is an alias of the package function of the same name.
func (LoggerFactory[E]) WithLevel(level Level) Option[E] {
return WithLevel[E](level)
}
// WithDPanicLevel configures the level that the [Logger.DPanic] method will
// alias to, defaulting to [LevelCritical].
//
// See also LoggerFactory.WithDPanicLevel and L (an instance of
// LoggerFactory[Event]{}).
func WithDPanicLevel[E Event](level Level) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.dpanic = level
})
}
// WithDPanicLevel is an alias of the package function of the same name.
func (LoggerFactory[E]) WithDPanicLevel(level Level) Option[E] {
return WithDPanicLevel[E](level)
}
// WithCategoryRateLimits configures the logger to support category-based rate limiting.
//
// Rate limits may be enabled on a per-event basis, see also [Builder.Limit],
// and [Logger.CallerCategoryRateLimitModifier].
//
// There are specific constraints on the map keys and values:
//
// 1. The key (duration) must be greater than zero
// 2. The value (count) must be greater than zero
// 3. The count must be less than that of any longer durations
// 4. The effective rate (count/duration) must be less than that of any shorter durations
func WithCategoryRateLimits[E Event](rates map[time.Duration]int) Option[E] {
return optionFunc[E](func(c *loggerConfig[E]) {
c.categoryRateLimits = rates
})
}
// WithCategoryRateLimits is an alias of the package function of the same name.
func (LoggerFactory[E]) WithCategoryRateLimits(rates map[time.Duration]int) Option[E] {
return WithCategoryRateLimits[E](rates)
}
// New constructs a new Logger instance.
//
// Configure the logger using either the With* prefixed functions (or methods
// of LoggerFactory, e.g. accessible via the L global), or via composite
// options, implemented in external packages, e.g. logger integrations.
//
// See also LoggerFactory.New and L (an instance of LoggerFactory[Event]{}).
func New[E Event](options ...Option[E]) (logger *Logger[E]) {
c := loggerConfig[E]{
level: LevelInformational,
dpanic: LevelCritical,
}
WithOptions(options...).apply(&c)
shared := loggerShared[E]{
level: c.level,
factory: c.factory,
releaser: c.releaser,
writer: c.resolveWriter(),
json: c.resolveJSONSupport(),
dpanic: c.dpanic,
catrate: c.resolveCategoryRateLimiter(),
}
shared.init()
logger = &Logger[E]{
modifier: c.resolveModifier(),
shared: &shared,
}
shared.root = logger
return
}
// New is an alias of the package function of the same name.
//
// See also LoggerFactory.New and L (an instance of LoggerFactory[Event]{}).
func (LoggerFactory[E]) New(options ...Option[E]) *Logger[E] {
return New[E](options...)
}
// Level returns the logger's [Level], note that it will be [LevelDisabled] if
// it isn't writeable, or if the provided level was any disabled value.
func (x *Logger[E]) Level() Level {
if x.Enabled() && x.shared.level.Enabled() {
return x.shared.level
}
return LevelDisabled
}
// Root returns the root [Logger] for this instance.
func (x *Logger[E]) Root() *Logger[E] {
if x != nil && x.shared != nil {
return x.shared.root
}
return nil
}
// Logger returns a new generified logger.
//
// Use this for greater compatibility, but sacrificing ease of using the
// underlying library directly.
func (x *Logger[E]) Logger() (logger *Logger[Event]) {
if x, ok := any(x).(*Logger[Event]); ok {
return x
}
if x == nil || x.shared == nil {
return nil
}
logger = &Logger[Event]{
modifier: generifyModifier(x.modifier),
shared: &loggerShared[Event]{
level: x.shared.level,
factory: generifyEventFactory(x.shared.factory),
releaser: generifyEventReleaser(x.shared.releaser),
writer: generifyWriter(x.shared.writer),
pool: &genericBuilderPool,
json: generifyJSONSupport(x.shared.json),
},
}
logger.shared.root = logger
return
}
// Log directly performs a Log operation, without the "fluent builder" pattern.
func (x *Logger[E]) Log(level Level, modifier Modifier[E]) error {
if !x.canLog(level) {
return ErrDisabled
}
event := x.newEvent(level)
if x.shared.releaser != nil {
defer x.shared.releaser.ReleaseEvent(event)
}
if x.modifier != nil {
if err := x.modifier.Modify(event); err != nil {
return err
}
}
if modifier != nil {
if err := modifier.Modify(event); err != nil {
return err
}
}
return x.shared.writer.Write(event)
}
// Build returns a new Builder for the given level, note that it may return nil
// (e.g. if the level is disabled).
//
// See also the methods Info, Debug, etc.
func (x *Logger[E]) Build(level Level) *Builder[E] {
// WARNING must mirror flow of the Log method
if !x.canLog(level) {
return nil
}
// initialise the builder
b := x.shared.newBuilder(x.newEvent(level))
// apply the logger's modifier, if any
return b.Modifier(x.modifier)
}
func (x *loggerShared[E]) newBuilder(event E) *Builder[E] {
b := x.pool.Get().(*Builder[E])
b.Event = event
b.shared = x
return b
}
// Clone returns a new Context, which is a mechanism to configure a sub-logger,
// which will be available via Context.Logger, note that it may return nil.
func (x *Logger[E]) Clone() *Context[E] {
if !x.Enabled() {
return nil
}
var c Context[E]
if x.modifier != nil {
c.Modifiers = append(c.Modifiers, x.modifier)
}
c.logger = &Logger[E]{
modifier: ModifierFunc[E](func(event E) error {
return c.Modifiers.Modify(event)
}),
shared: x.shared,
}
return &c
}
// Emerg is an alias for Logger.Build(LevelEmergency).
func (x *Logger[E]) Emerg() *Builder[E] { return x.Build(LevelEmergency) }
// Alert is an alias for Logger.Build(LevelAlert).
func (x *Logger[E]) Alert() *Builder[E] { return x.Build(LevelAlert) }
// Crit is an alias for Logger.Build(LevelCritical).
func (x *Logger[E]) Crit() *Builder[E] { return x.Build(LevelCritical) }
// Err is an alias for Logger.Build(LevelError).
func (x *Logger[E]) Err() *Builder[E] { return x.Build(LevelError) }
// Warning is an alias for Logger.Build(LevelWarning).
func (x *Logger[E]) Warning() *Builder[E] { return x.Build(LevelWarning) }
// Notice is an alias for Logger.Build(LevelNotice).
func (x *Logger[E]) Notice() *Builder[E] { return x.Build(LevelNotice) }
// Info is an alias for Logger.Build(LevelInformational).
func (x *Logger[E]) Info() *Builder[E] { return x.Build(LevelInformational) }
// Debug is an alias for Logger.Build(LevelDebug).
func (x *Logger[E]) Debug() *Builder[E] { return x.Build(LevelDebug) }
// Trace is an alias for Logger.Build(LevelTrace).
func (x *Logger[E]) Trace() *Builder[E] { return x.Build(LevelTrace) }
// Fatal constructs a [Builder] that behaves like [Logger.Alert], with the
// additional behaviour that it will call [os.Exit](1) after the event has been
// written.
//
// The recommended behavior is to map [LevelAlert] to a "fatal level", and most
// log libraries seem to have their own implementation, so they may trigger the
// actual exit.
//
// WARNING: An exit will occur immediately if that level is disabled.
//
// See also [OsExit].
func (x *Logger[E]) Fatal() (b *Builder[E]) {
b = x.Build(LevelAlert)
if b == nil {
_, _ = fmt.Fprintln(os.Stderr, `logiface: fatal requested but logger is disabled`)
OsExit(1)
return nil
}
b.mode |= builderModeFatal
return b
}
// Panic constructs a [Builder] that behaves like [Logger.Emerg], with the
// additional behaviour that it will panic after the event has been written.
//
// The recommended behavior is to map [LevelEmergency] to a "panic level", and
// most log libraries seem to have their own implementation, so they may
// trigger the actual panic.
//
// WARNING: A panic will occur immediately if that level is disabled.
func (x *Logger[E]) Panic() (b *Builder[E]) {
b = x.Build(LevelEmergency)
if b == nil {
panic(`logiface: panic requested but logger is disabled`)
}
b.mode |= builderModePanic
return
}
// DPanic is a virtual log level, and stands for "panic in development". It is
// intended to be used for errors that "shouldn't happen", but, if they occur
// in production, shouldn't (necessarily) trigger an actual panic.
//
// If configured with LevelEmergency, it will behave like [Logger.Panic],
// otherwise it will behave like [Logger.Build](dpanicLevel).
//
// It's default level is [LevelCritical], intended for production use.
// See also [WithDPanicLevel].
//
// This method was inspired by
// [zap](https://github.com/uber-go/zap/blob/85c4932ce3ea76b6babe3e0a3d79da10ef295b8d/FAQ.md#whats-dpanic).
func (x *Logger[E]) DPanic() *Builder[E] {
if x != nil && x.shared != nil {
if x.shared.dpanic == LevelEmergency {
return x.Panic()
}
return x.Build(x.shared.dpanic)
}
return nil
}
// Enabled returns true if the logger can write.
func (x *Logger[E]) Enabled() bool {
return x != nil &&
x.shared != nil &&
x.shared.writer != nil
}
func (x *Logger[E]) canLog(level Level) bool {
return x.Enabled() &&
level.Enabled() &&
(level <= x.shared.level || level > LevelTrace)
}
func (x *Logger[E]) newEvent(level Level) (event E) {
if x != nil && x.shared != nil && x.shared.factory != nil {
event = x.shared.factory.NewEvent(level)
}
return
}
func (x *loggerShared[E]) init() {
switch any(x).(type) {
case *loggerShared[Event]:
x.pool = &genericBuilderPool
default:
x.pool = &sync.Pool{New: newBuilder[E]}
}
}
func (x *loggerConfig[E]) resolveWriter() Writer[E] {
switch len(x.writer) {
case 0:
return nil
case 1:
return x.writer[0]
default:
reverseSlice(x.writer)
return x.writer
}
}
func (x *loggerConfig[E]) resolveModifier() Modifier[E] {
switch len(x.modifier) {
case 0:
return nil
case 1:
return x.modifier[0]
default:
return x.modifier
}
}
func (x *loggerConfig[E]) resolveJSONSupport() *jsonSupport[E] {
if x.json != nil {
return x.json
}
return newJSONSupport[E, map[string]any, []any](defaultJSONSupport[E]{})
}
func (x *loggerConfig[E]) resolveCategoryRateLimiter() *catrate.Limiter {
if len(x.categoryRateLimits) != 0 {
return catrate.NewLimiter(maps.Clone(x.categoryRateLimits))
}
return nil
}
func reverseSlice[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func generifyModifier[E Event](modifier Modifier[E]) Modifier[Event] {
if modifier == nil {
return nil
}
return ModifierFunc[Event](func(event Event) error {
return modifier.Modify(event.(E))
})
}
func generifyWriter[E Event](writer Writer[E]) Writer[Event] {
if writer == nil {
return nil
}
return WriterFunc[Event](func(event Event) error {
return writer.Write(event.(E))
})
}
func generifyEventFactory[E Event](factory EventFactory[E]) EventFactory[Event] {
if factory == nil {
return nil
}
return EventFactoryFunc[Event](func(level Level) Event {
return factory.NewEvent(level)
})
}
func generifyEventReleaser[E Event](releaser EventReleaser[E]) EventReleaser[Event] {
if releaser == nil {
return nil
}
return EventReleaserFunc[Event](func(event Event) {
releaser.ReleaseEvent(event.(E))
})
}
func newBuilder[E Event]() any {
return new(Builder[E])
}