Repository navigation
Expand file tree
/
Copy pathoptions.go
More file actions
393 lines (375 loc) · 12.9 KB
/
Copy pathoptions.go
File metadata and controls
393 lines (375 loc) · 12.9 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
package axio
import (
"errors"
"fmt"
"slices"
"go.opentelemetry.io/otel/metric"
)
// Option is a function that configures the [Logger] during creation.
//
// Options follow Go's functional configuration pattern, allowing
// flexible and extensible configuration. Use with [New].
//
// Precedence order is: Config (file) → Options → Defaults.
// Options always override Config values.
//
// Available options:
// - [WithOutputs]: configures output destinations
// - [WithAgentMode]: optimizes for collection by external agents
// - [WithOmitCaller]: writes lines without the caller
// - [WithHooks]: configures custom processing hooks
// - [WithPII]: configures PII masking
// - [WithPIIDisabled]: turns PII masking off
// - [WithPIIMaxDepth]: sets how deep PII masking walks into structured values
// - [WithPIIIdentifierShapes]: declares identifiers that PII masking leaves as they are
// - [WithPIIOmitErrorVerbose]: omits the verbose form of errors instead of masking it
// - [WithAudit]: configures auditing with a hash chain stored in a file
// - [WithAuditChain]: configures auditing with a hash chain of your own
// - [WithMetrics]: configures metrics collection
// - [WithTracer]: configures trace extraction
type Option func(*Config) error
// WithOutputs configures the logger to write to the specified destinations.
//
// Multiple outputs can be specified for simultaneous writing to
// different destinations. Each output can have its own format.
//
// This function accepts [Output] objects and converts them internally to [OutputConfig].
// For file-based configuration, use the [Config.Outputs] field directly.
//
// Options override the Config: the first WithOutputs replaces the outputs in
// [Config.Outputs], which are then neither opened nor validated, and later
// calls add to it.
//
// Example:
//
// logger, _ := axio.New(config,
// axio.WithOutputs(
// axio.Console(axio.FormatText), // development
// axio.Stdout(axio.FormatJSON), // collection agent
// axio.MustFile("/var/log/app.log", axio.FormatJSON), // file
// ),
// )
func WithOutputs(outputs ...Output) Option {
return func(config *Config) error {
if len(outputs) > 0 && len(config.resolvedOutputs) == 0 {
config.Outputs = nil
}
for _, output := range outputs {
config.resolvedOutputs = append(config.resolvedOutputs, output)
// Mirror metadata so Validate() and AgentMode rules — which
// iterate config.Outputs — still apply. The file handle stays
// owned by the resolved output; no Close/Reopen dance.
outputConfig := OutputConfig{
Type: output.Type(),
Format: output.Format(),
}
if fileOut, ok := output.(*fileOutput); ok {
outputConfig.Path = fileOut.path
}
config.Outputs = append(config.Outputs, outputConfig)
}
return nil
}
}
// WithAgentMode configures the logger for use with external log collection
// agents like Promtail, Fluent Bit, or Filebeat.
//
// This option:
// - Sets [Config.AgentMode] to true
// - Forces output to stdout with JSON format
// - Overwrites any previous output, closing the ones passed to an earlier
// [WithOutputs]; an error closing them is returned
//
// When this option is used, logs are written to stdout in JSON format,
// allowing external agents to collect and forward them to aggregation
// systems like Loki, Elasticsearch, or Splunk.
//
// Example:
//
// logger, _ := axio.New(config, axio.WithAgentMode())
func WithAgentMode() Option {
return func(config *Config) error {
config.AgentMode = true
config.Outputs = []OutputConfig{
{
Type: OutputStdout,
Format: FormatJSON,
},
}
// WithOutputs handed these to the logger, and the logger will no longer
// hold them, so nothing else is left to close them.
discarded := config.resolvedOutputs
config.resolvedOutputs = nil
var errs []error
for _, output := range discarded {
if err := closeDiscarded(output); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
}
// WithHooks configures the logger to process log entries through the specified hooks.
//
// Hooks run in the order they were registered, after PII masking and before
// the entry is written; with auditing on, the hash covers what they changed.
// If a hook returns an error, processing stops and the entry is not written.
//
// For PII masking, prefer [WithPII], which runs before every custom hook.
//
// Example:
//
// logger, _ := axio.New(config,
// axio.WithHooks(myCustomHook),
// )
func WithHooks(hooks ...Hook) Option {
return func(config *Config) error {
config.hooks = append(config.hooks, hooks...)
return nil
}
}
// WithPII sets the patterns and fields PII masking uses. Masking is on by
// default; WithPII also turns it back on over a [Config.PIIDisabled] loaded
// from a file, as options override the file.
//
// If patterns is nil or empty, uses default patterns (CPF, CNPJ, CreditCard).
// If fields is nil or empty, uses [DefaultSensitiveFields].
//
// Masking covers the message, the error and every annotation, as
// [PIIMasker.MaskFields] describes, before any custom hook runs.
//
// Example:
//
// logger, _ := axio.New(config,
// axio.WithPII(
// []axio.PIIPattern{axio.PatternCPF, axio.PatternEmail},
// axio.DefaultSensitiveFields(),
// ),
// )
func WithPII(patterns []PIIPattern, fields []string) Option {
return func(config *Config) error {
config.PIIDisabled = false
if len(patterns) > 0 {
config.PIIPatterns = patterns
}
if len(fields) > 0 {
config.PIIFields = fields
}
return nil
}
}
// WithPIIDisabled turns off PII masking, which is on by default, as
// [Config.PIIDisabled] does from a file. The message, the error and every
// annotation are then written as given, and no entry pays for the scan.
//
// Example:
//
// logger, err := axio.New(config, axio.WithPIIDisabled())
func WithPIIDisabled() Option {
return func(config *Config) error {
config.PIIDisabled = true
return nil
}
}
// WithPIIMaxDepth sets how deep PII masking walks into a structured
// annotation value, as [Config.PIIMaxDepth] does from a file. A container
// nested deeper is replaced by "[REDACTED]" whole; zero means
// [DefaultPIIMaxDepth]. It has no effect with masking turned off by
// [WithPIIDisabled] or [Config.PIIDisabled].
//
// Returns [ErrInvalidPIIMaxDepth] for a negative depth.
//
// Example:
//
// logger, err := axio.New(config, axio.WithPIIMaxDepth(8))
func WithPIIMaxDepth(depth int) Option {
return func(config *Config) error {
if depth < 0 {
return fmt.Errorf("%w: %d", ErrInvalidPIIMaxDepth, depth)
}
config.PIIMaxDepth = depth
return nil
}
}
// WithPIIIdentifierShapes declares the shapes of identifiers that are not
// PII, as [Config.PIIIdentifierShapes] does from a file: a built-in pattern for
// a number — CPF, CNPJ, card, phone — never matches inside a match of one, so
// a file name carrying a timestamp is not masked as a CNPJ. The shapes replace
// those of the file, and none clears them. [PIIConfig.IdentifierShapes] says
// what a shape matches and which shapes are too broad. It has no effect with
// masking turned off by [WithPIIDisabled] or [Config.PIIDisabled], and the
// shapes are validated all the same.
//
// [New] returns [ErrValidateConfig] wrapping [ErrBroadPIIIdentifierShape] for a
// shape too broad, and [ErrInvalidPIIIdentifierShape] for one that is not RE2.
//
// Example:
//
// logger, err := axio.New(config,
// axio.WithPIIIdentifierShapes(`\d{14,23}-[0-9a-f]{64}\.csv`),
// )
func WithPIIIdentifierShapes(shapes ...string) Option {
shapes = slices.Clone(shapes)
return func(config *Config) error {
config.PIIIdentifierShapes = shapes
return nil
}
}
// WithPIIOmitErrorVerbose makes PII masking omit the verbose form of an error
// that formats itself — the %+v, a stack trace for many errors — instead of
// masking it, as [Config.PIIOmitErrorVerbose] does from a file. The error is
// then written by its masked message only, and its verbose form is never read,
// which spares scanning it: a stack of a couple of kilobytes costs about 250 µs
// to mask. It has no effect with masking turned off by [WithPIIDisabled] or
// [Config.PIIDisabled].
//
// Example:
//
// logger, err := axio.New(config, axio.WithPIIOmitErrorVerbose())
func WithPIIOmitErrorVerbose() Option {
return func(config *Config) error {
config.PIIOmitErrorVerbose = true
return nil
}
}
// WithOmitCaller writes lines without the caller, as [Config.OmitCaller] does
// from a file. Finding the caller walks the stack on every entry, and it can
// cost about half of writing a line; without it, [Entry.Caller] is empty for
// hooks and [Config.CallerSkip] has no effect.
//
// Example:
//
// logger, err := axio.New(config, axio.WithOmitCaller())
func WithOmitCaller() Option {
return func(config *Config) error {
config.OmitCaller = true
return nil
}
}
// WithAudit enables auditing with a hash chain whose state is persisted at
// storePath.
//
// Every JSON line then ends with previous_hash and hash: the SHA-256 of the
// previous line's hash followed by the line's own bytes, so the hash covers
// exactly what was written. Verify the log with [HashChain.Verify]. Text
// outputs show a shortened hash for reference only.
//
// Every Logger audited with the same storePath in this process, and every
// [Event] they start, extends one chain, whichever was created first. Another process holding the
// same store makes [New] fail with [ErrBuildAudit] wrapping
// [ErrChainStoreLocked]; see [FileStore]. An audited Logger needs a JSON
// output, or [New] returns [ErrAuditWithoutJSON].
//
// Example:
//
// logger, _ := axio.New(config,
// axio.WithAudit("/var/lib/axio/audit-chain.json"),
// )
func WithAudit(storePath string) Option {
return func(config *Config) error {
config.Audit.Enabled = true
config.Audit.StorePath = storePath
return nil
}
}
// WithAuditChain enables auditing through chain, for chain state kept in a
// [ChainStore] other than a local file. Loggers given the same chain, and the
// events they start, extend one chain.
//
// A chain over a [FileStore] is locked the way [WithAudit] locks its store:
// [New] takes the store's lock and loads the chain from it again,
// so a store another process holds fails there with [ErrChainStoreLocked], and
// state another process saved after [NewHashChain] loaded it is continued.
//
// Returns [ErrNilAuditChain] if chain is nil.
//
// Example:
//
// chain, err := axio.NewHashChain(redisStore)
// if err != nil {
// return err
// }
// logger, err := axio.New(config, axio.WithAuditChain(chain))
func WithAuditChain(chain *HashChain) Option {
return func(config *Config) error {
if chain == nil {
return ErrNilAuditChain
}
config.Audit.Enabled = true
config.auditChain = chain
return nil
}
}
// WithMetrics configures the logger to emit metrics using the specified
// OpenTelemetry MeterProvider.
//
// If provider is nil, returns [ErrNilMetricsProvider].
//
// Emitted metrics include:
// - logs.total: Log counter by level
// - pii.masked: Masked PII counter by pattern and origin
// - pii.redacted: Counter of values redacted whole, by reason and origin
// - audit.records: Audit records counter
// - hook.duration: Hook duration histogram
//
// Example:
//
// provider := otel.GetMeterProvider()
// logger, err := axio.New(config, axio.WithMetrics(provider))
func WithMetrics(provider metric.MeterProvider) Option {
return func(config *Config) error {
if provider == nil {
return ErrNilMetricsProvider
}
config.Metrics.Enabled = true
config.metricsProvider = provider
return nil
}
}
// WithTracer configures the logger to extract trace information from context.
//
// When configured, the logger automatically adds trace_id and span_id
// to each log entry, enabling correlation between logs and traces in
// observability systems like Jaeger, Tempo, or Zipkin.
//
// Available tracers:
// - [Otel]: extracts from OpenTelemetry spans
// - [NoopTracing]: never extracts information (default)
//
// Example:
//
// logger, _ := axio.New(config, axio.WithTracer(axio.Otel()))
//
// // In an HTTP handler with active span
// func handleRequest(w http.ResponseWriter, r *http.Request) {
// ctx := r.Context() // contains span from otel middleware
// logger.Info(ctx, "request received")
// // Log will include: {"trace_id": "abc123...", "span_id": "def456..."}
// }
func WithTracer(tracer Tracer) Option {
return func(config *Config) error {
if tracer == nil {
return ErrNilTracer
}
config.tracer = tracer
// Detects tracer type for serialization
switch tracer.(type) {
case *otelTraceExtractor:
config.TracerType = "otel"
default:
config.TracerType = "noop"
}
return nil
}
}
// closeDiscarded closes an output [WithAgentMode] discards. A file output is
// claimed first, so one that belongs to another Logger is left open and
// reported with [ErrOutputInUse], as [New] would report it.
func closeDiscarded(output Output) error {
if file, ok := output.(*fileOutput); ok {
if err := file.claim(); err != nil {
return err
}
}
return output.Close()
}