Repository navigation
Expand file tree
/
Copy pathlogger.go
More file actions
510 lines (450 loc) · 14.4 KB
/
Copy pathlogger.go
File metadata and controls
510 lines (450 loc) · 14.4 KB
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
package axio
import (
"context"
"errors"
"fmt"
"os"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/pragmabits/axio/internal/logline"
)
const minimumCallerSkip = 2
var entryPool = sync.Pool{
New: func() any { return &Entry{} },
}
type logger struct {
engine *zap.Logger
eventEngine *zap.Logger
trace Tracer
hooks *hookChain
metrics Metrics
annotations []Annotation
outputs []Output
lifecycle *lifecycle
isFork bool
audited bool
}
// New creates a new [Logger] with the specified configuration and options.
//
// The application order is:
// 1. Initial Config (loaded from file or created programmatically)
// 2. Options are applied (override Config values)
// 3. Defaults are applied (fill empty fields)
// 4. Final validation
//
// If no output is specified, the default behavior is:
// - Development environment: Console with [FormatText] (colored)
// - Other environments: Stdout with [FormatJSON] (structured)
//
// The function returns [ErrApplyOption] if any option fails to be applied
// or [ErrValidateConfig] if the resulting configuration is invalid — an
// audited Logger with no JSON output included, wrapping [ErrAuditWithoutJSON],
// since only JSON lines can be verified.
//
// Basic example:
//
// config := axio.Config{
// ServiceName: "sales-api",
// ServiceVersion: "2.1.0",
// Environment: axio.EnvironmentProduction,
// Level: axio.LevelInfo,
// }
// logger, err := axio.New(config)
// if err != nil {
// return fmt.Errorf("failed to create logger: %w", err)
// }
//
// Example with file and options:
//
// config, _ := axio.LoadConfig("config.yaml")
// logger, err := axio.New(config,
// axio.WithOutputs(axio.Stdout(axio.FormatJSON)),
// axio.WithTracer(axio.Otel()),
// )
func New(config Config, options ...Option) (Logger, error) {
for _, option := range options {
if err := option(&config); err != nil {
return nil, fmt.Errorf("%w: %w", ErrApplyOption, err)
}
}
applyDefaults(&config)
if err := config.Validate(); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidateConfig, err)
}
if err := config.validateAuditOutputs(); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidateConfig, err)
}
outputs, err := openOutputs(config)
if err != nil {
return nil, err
}
parts, err := buildEngineParts(config)
if err != nil {
return nil, abandonOutputs(config, outputs, err)
}
engine, err := buildEngine(config, outputs, parts)
if err != nil {
return nil, abandonOutputs(config, outputs, fmt.Errorf("%w: %w", ErrBuildEngine, err))
}
return &logger{
engine: engine,
eventEngine: buildEventEngine(outputs, parts),
trace: buildTracer(config),
hooks: newHookChain(parts.metrics, parts.hooks...),
metrics: parts.metrics,
outputs: outputs,
lifecycle: new(lifecycle),
audited: parts.chain != nil,
}, nil
}
func (l logger) Named(name string) Logger {
l.engine = l.engine.Named(name)
l.annotations = cloneAnnotations(l.annotations)
l.isFork = true
return &l
}
func (l logger) With(annotations ...Annotation) Logger {
combined := make([]Annotation, 0, len(l.annotations)+len(annotations))
combined = append(combined, l.annotations...)
combined = append(combined, annotations...)
l.annotations = combined
l.isFork = true
return &l
}
func (l *logger) Event(name string) *Event {
inherited := len(l.annotations)
return &Event{
name: name,
loggerName: l.engine.Name(),
engine: l.eventEngine,
hooks: l.hooks,
trace: l.trace,
annotations: l.annotations[:inherited:inherited],
lifecycle: l.lifecycle,
audited: l.audited,
startTime: time.Now(),
}
}
func (l logger) Debug(ctx context.Context, message string, annotations ...Annotation) {
l.log(ctx, LevelDebug, nil, message, annotations)
}
func (l logger) Info(ctx context.Context, message string, annotations ...Annotation) {
l.log(ctx, LevelInfo, nil, message, annotations)
}
func (l logger) Warn(ctx context.Context, err error, message string, annotations ...Annotation) {
l.log(ctx, LevelWarn, err, message, annotations)
}
func (l logger) Error(ctx context.Context, err error, message string, annotations ...Annotation) {
l.log(ctx, LevelError, err, message, annotations)
}
func (l *logger) Close() error {
if l.isFork {
return ErrLoggerNotRoot
}
l.lifecycle.mutex.Lock()
defer l.lifecycle.mutex.Unlock()
if !l.lifecycle.closed.CompareAndSwap(false, true) {
return ErrLoggerClosed
}
var errs []error
if err := l.engine.Sync(); err != nil {
errs = append(errs, fmt.Errorf("sync engine: %w", err))
}
for _, out := range l.outputs {
if err := out.Close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return fmt.Errorf("close logger: %w", errors.Join(errs...))
}
return nil
}
func (l *logger) log(
ctx context.Context,
level Level,
err error,
message string,
annotations []Annotation,
) {
if l.lifecycle.closed.Load() {
return
}
log := l.engine.Check(toZapLevel(level), message)
if log == nil {
return
}
trace, span, _ := l.trace.Extract(ctx)
entry := entryPool.Get().(*Entry)
entry.Timestamp = log.Time
entry.Logger = log.LoggerName
if log.Caller.Defined && l.hooks.readsCaller() {
entry.Caller = log.Caller.TrimmedPath()
}
entry.Level = level
entry.Message = log.Message
entry.Error = err
entry.TraceID = trace
entry.SpanID = span
entry.Annotations = expandAnnotable(cloneAnnotations(l.annotations, annotations))
defer func() {
*entry = Entry{}
entryPool.Put(entry)
}()
if err := l.hooks.process(ctx, entry); err != nil {
fmt.Fprintf(os.Stderr, "axio: hook error: %v\n", err)
return
}
log.Message = entry.Message
fields := l.fieldsFromEntry(entry)
if l.audited {
fields = append(fields, contextField(ctx))
}
if l.lifecycle.write(log, fields) {
l.metrics.LogsTotal(ctx, level)
}
}
func (l *logger) fieldsFromEntry(entry *Entry) []zap.Field {
var backing [5]zap.Field
fields := backing[:0]
if entry.TraceID != "" {
fields = append(fields, zap.String(logline.TraceIDKey, entry.TraceID))
}
if entry.SpanID != "" {
fields = append(fields, zap.String(logline.SpanIDKey, entry.SpanID))
}
if entry.Error != nil {
fields = append(fields, zap.NamedError(logline.ErrorKey, entry.Error))
}
if annotationFields := annotationsToFields(entry.Annotations); annotationFields != nil {
fields = append(fields, annotationFields...)
}
return fields
}
// engineParts are what [New] builds between the outputs and the engines.
type engineParts struct {
metrics Metrics
hooks []Hook
chain *HashChain
}
// buildEngineParts builds the metrics, the hooks and the audit chain of config,
// returning [ErrBuildMetrics], [ErrBuildHooks] or [ErrBuildAudit] for the one
// that fails.
func buildEngineParts(config Config) (engineParts, error) {
metrics, err := buildMetrics(config)
if err != nil {
return engineParts{}, fmt.Errorf("%w: %w", ErrBuildMetrics, err)
}
hooks, err := buildHooks(config)
if err != nil {
return engineParts{}, fmt.Errorf("%w: %w", ErrBuildHooks, err)
}
chain, err := buildAuditChain(config)
if err != nil {
return engineParts{}, fmt.Errorf("%w: %w", ErrBuildAudit, err)
}
return engineParts{metrics: metrics, hooks: hooks, chain: chain}, nil
}
// buildEngine builds the zap logger behind a Logger: an audited core when
// there is a chain, one plain core per output otherwise.
func buildEngine(config Config, outputs []Output, parts engineParts) (*zap.Logger, error) {
level := zap.NewAtomicLevelAt(toZapLevel(config.Level))
metadata := serviceMetadata(config)
var core zapcore.Core
if parts.chain != nil {
core = newAuditedCore(level, outputs, metadata, parts, entryEncoding())
} else {
core = newPlainCore(level, outputs, metadata, entryEncoding())
}
core = &reportingCore{Core: core}
var options []zap.Option
if !config.OmitCaller {
options = append(options, zap.AddCaller(), zap.AddCallerSkip(config.CallerSkip+minimumCallerSkip))
}
if config.Environment != EnvironmentDevelopment {
options = append(options, zap.AddStacktrace(zapcore.ErrorLevel))
}
return zap.New(core, options...), nil
}
// newPlainCore writes each output in its own format, in the line's encoding.
// Only JSON outputs carry the service metadata: in text it would repeat the
// same fields on every line.
func newPlainCore(level zapcore.LevelEnabler, outputs []Output, metadata []zapcore.Field, encoding lineEncoding) zapcore.Core {
cores := make([]zapcore.Core, 0, len(outputs))
for _, output := range outputs {
core := zapcore.NewCore(encoding.encoder(output.Format()), output, level)
if output.Format() == FormatJSON {
core = core.With(metadata)
}
cores = append(cores, core)
}
return zapcore.NewTee(cores...)
}
// newAuditedCore writes every output through the audit chain, in the line's
// encoding. The hash covers the JSON encoding, service metadata included; text
// outputs get the entry without metadata and with the hash shortened.
func newAuditedCore(level zapcore.LevelEnabler, outputs []Output, metadata []zapcore.Field, parts engineParts, encoding lineEncoding) zapcore.Core {
core := &auditCore{
LevelEnabler: level,
chain: parts.chain,
metrics: parts.metrics,
canonical: zapcore.NewJSONEncoder(encoding.json),
}
addFields(core.canonical, metadata)
for _, output := range outputs {
if output.Format() == FormatJSON {
core.jsonOutputs = append(core.jsonOutputs, output)
continue
}
core.textSinks = append(core.textSinks, textSink{encoder: encoding.encoder(output.Format()), output: output})
}
return core
}
// lifecycle is whether a root Logger is still open, shared by its forks and by
// the events they start. A write holds its lock for reading from its last look
// at closed to the end of the write, and Close holds it for writing while it
// closes the outputs, so a write either finishes before the outputs close or
// finds the logger closed and writes nothing: no write fails on an output
// already closed, reaches one output and not another, or, with auditing, takes
// the chain past the log.
type lifecycle struct {
mutex sync.RWMutex
closed atomic.Bool
}
// write writes the checked entry unless the logger has closed, holding the
// lock for reading so Close waits for it, and reports whether it wrote.
func (l *lifecycle) write(log *zapcore.CheckedEntry, fields []zap.Field) bool {
l.mutex.RLock()
defer l.mutex.RUnlock()
if l.closed.Load() {
return false
}
log.Write(fields...)
return true
}
// reportingCore reports a failed write on stderr as one line prefixed axio:,
// as the rest of the log path reports what it cannot return, and keeps the
// error from zap, which would print it again in its own format.
type reportingCore struct {
zapcore.Core
}
func (r *reportingCore) With(fields []zapcore.Field) zapcore.Core {
return &reportingCore{Core: r.Core.With(fields)}
}
func (r *reportingCore) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if r.Enabled(entry.Level) {
return checked.AddCore(entry, r)
}
return checked
}
func (r *reportingCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
if err := r.Core.Write(entry, fields); err != nil {
fmt.Fprintf(os.Stderr, "axio: write error: %v\n", err)
}
return nil
}
// serviceMetadata returns the service and deployment fields a JSON line
// carries outside [EnvironmentDevelopment].
func serviceMetadata(config Config) []zapcore.Field {
if config.Environment == EnvironmentDevelopment {
return nil
}
return []zapcore.Field{
zap.Any(logline.ServiceKey, map[string]any{
"name": config.ServiceName,
"version": config.ServiceVersion,
"instance": map[string]any{
"id": config.InstanceID,
},
}),
zap.Any(logline.DeploymentKey, map[string]any{
"environment": map[string]any{
"name": config.Environment,
},
}),
}
}
// lineEncoding is the encoder settings a kind of line is written with: in JSON,
// and in the Console's text.
type lineEncoding struct {
json zapcore.EncoderConfig
text zapcore.EncoderConfig
}
// entryEncoding returns the encoding of a log entry.
func entryEncoding() lineEncoding {
return lineEncoding{json: logline.JSONEncoderConfig(), text: logline.ConsoleEncoderConfig()}
}
// eventEncoding returns the encoding of a wide event.
func eventEncoding() lineEncoding {
return lineEncoding{json: logline.EventEncoderConfig(), text: logline.EventConsoleEncoderConfig()}
}
// encoder returns the encoder of an output in format.
func (l lineEncoding) encoder(format Format) zapcore.Encoder {
if format == FormatText {
return zapcore.NewConsoleEncoder(l.text)
}
return zapcore.NewJSONEncoder(l.json)
}
func toZapLevel[T ~string | ~[]byte](level T) zapcore.Level {
parsed, _ := zapcore.ParseLevel(string(level))
return parsed
}
// cloneAnnotations returns a fresh slice holding the annotations of every
// source, in order. Used when forking a logger and when handing annotations to
// hooks, to break aliasing with the backing arrays of the parent and of the
// caller, so mutations (e.g. by hooks) reach neither.
func cloneAnnotations(sources ...[]Annotation) []Annotation {
length := 0
for _, source := range sources {
length += len(source)
}
if length == 0 {
return nil
}
clone := make([]Annotation, 0, length)
for _, source := range sources {
clone = append(clone, source...)
}
return clone
}
// annotationsToFields returns the fields the annotations are written as, each
// under [logline.FieldKey] of its name.
func annotationsToFields(annotations []Annotation) []zap.Field {
if len(annotations) == 0 {
return nil
}
expanded := expandAnnotable(annotations)
fields := make([]zap.Field, len(expanded))
for index := range expanded {
fields[index] = expanded[index].field
fields[index].Key = logline.FieldKey(fields[index].Key)
}
return fields
}
// expandAnnotable replaces Annotable annotations with their expanded fields. A
// logger expands them before the hooks run, so PII masking sees each field;
// serialization expands what a hook added after that.
func expandAnnotable(annotations []Annotation) []Annotation {
hasAnnotable := false
for _, annotation := range annotations {
if _, ok := annotation.field.Interface.(Annotable); ok {
hasAnnotable = true
break
}
}
if !hasAnnotable {
return annotations
}
expanded := make([]Annotation, 0, len(annotations))
for _, annotation := range annotations {
if provider, ok := annotation.field.Interface.(Annotable); ok {
expanded = provider.Append(expanded)
} else {
expanded = append(expanded, annotation)
}
}
return expanded
}