Debian Codegraph @

modules/logging/filterencoder.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package logging
16
17 import (
18 "encoding/json"
19 "fmt"
20 "os"
21 "time"
22
23 "go.uber.org/zap"
24 "go.uber.org/zap/buffer"
25 "go.uber.org/zap/zapcore"
26 "golang.org/x/term"
27
28 "github.com/caddyserver/caddy/v2"
29 "github.com/caddyserver/caddy/v2/caddyconfig"
30 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
31 )
32
33 func init() {
34 caddy.RegisterModule(FilterEncoder{})
35 }
36
37 // FilterEncoder can filter (manipulate) fields on
38 // log entries before they are actually encoded by
39 // an underlying encoder.
40 type FilterEncoder struct {
41 // The underlying encoder that actually encodes the
42 // log entries. If not specified, defaults to "json",
43 // unless the output is a terminal, in which case
44 // it defaults to "console".
45 WrappedRaw json.RawMessage `json:"wrap,omitempty" caddy:"namespace=caddy.logging.encoders inline_key=format"`
46
47 // A map of field names to their filters. Note that this
48 // is not a module map; the keys are field names.
49 //
50 // Nested fields can be referenced by representing a
51 // layer of nesting with `>`. In other words, for an
52 // object like `{"a":{"b":0}}`, the inner field can
53 // be referenced as `a>b`.
54 //
55 // The following fields are fundamental to the log and
56 // cannot be filtered because they are added by the
57 // underlying logging library as special cases: ts,
58 // level, logger, and msg.
59 FieldsRaw map[string]json.RawMessage `json:"fields,omitempty" caddy:"namespace=caddy.logging.encoders.filter inline_key=filter"`
60
61 wrapped zapcore.Encoder
62 Fields map[string]LogFieldFilter `json:"-"`
63
64 // used to keep keys unique across nested objects
65 keyPrefix string
66
67 wrappedIsDefault bool
68 ctx caddy.Context
69 }
70
71 // CaddyModule returns the Caddy module information.
72 func (FilterEncoder) CaddyModule() caddy.ModuleInfo {
73 return caddy.ModuleInfo{
74 ID: "caddy.logging.encoders.filter",
75 New: func() caddy.Module { return new(FilterEncoder) },
76 }
77 }
78
79 // Provision sets up the encoder.
80 func (fe *FilterEncoder) Provision(ctx caddy.Context) error {
81 fe.ctx = ctx
82
83 if fe.WrappedRaw == nil {
84 // if wrap is not specified, default to JSON
85 fe.wrapped = &JSONEncoder{}
86 if p, ok := fe.wrapped.(caddy.Provisioner); ok {
87 if err := p.Provision(ctx); err != nil {
88 return fmt.Errorf("provisioning fallback encoder module: %v", err)
89 }
90 }
91 fe.wrappedIsDefault = true
92 } else {
93 // set up wrapped encoder
94 val, err := ctx.LoadModule(fe, "WrappedRaw")
95 if err != nil {
96 return fmt.Errorf("loading fallback encoder module: %v", err)
97 }
98 fe.wrapped = val.(zapcore.Encoder)
99 }
100
101 // set up each field filter
102 if fe.Fields == nil {
103 fe.Fields = make(map[string]LogFieldFilter)
104 }
105 vals, err := ctx.LoadModule(fe, "FieldsRaw")
106 if err != nil {
107 return fmt.Errorf("loading log filter modules: %v", err)
108 }
109 for fieldName, modIface := range vals.(map[string]any) {
110 fe.Fields[fieldName] = modIface.(LogFieldFilter)
111 }
112
113 return nil
114 }
115
116 // ConfigureDefaultFormat will set the default format to "console"
117 // if the writer is a terminal. If already configured as a filter
118 // encoder, it passes through the writer so a deeply nested filter
119 // encoder can configure its own default format.
120 func (fe *FilterEncoder) ConfigureDefaultFormat(wo caddy.WriterOpener) error {
121 if !fe.wrappedIsDefault {
122 if cfd, ok := fe.wrapped.(caddy.ConfiguresFormatterDefault); ok {
123 return cfd.ConfigureDefaultFormat(wo)
124 }
125 return nil
126 }
127
128 if caddy.IsWriterStandardStream(wo) && term.IsTerminal(int(os.Stderr.Fd())) {
129 fe.wrapped = &ConsoleEncoder{}
130 if p, ok := fe.wrapped.(caddy.Provisioner); ok {
131 if err := p.Provision(fe.ctx); err != nil {
132 return fmt.Errorf("provisioning fallback encoder module: %v", err)
133 }
134 }
135 }
136 return nil
137 }
138
139 // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax:
140 //
141 // filter {
142 // wrap <another encoder>
143 // fields {
144 // <field> <filter> {
145 // <filter options>
146 // }
147 // }
148 // <field> <filter> {
149 // <filter options>
150 // }
151 // }
152 func (fe *FilterEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
153 d.Next() // consume encoder name
154
155 // Track regexp filters for automatic merging
156 regexpFilters := make(map[string][]*RegexpFilter)
157
158 // parse a field
159 parseField := func() error {
160 if fe.FieldsRaw == nil {
161 fe.FieldsRaw = make(map[string]json.RawMessage)
162 }
163 field := d.Val()
164 if !d.NextArg() {
165 return d.ArgErr()
166 }
167 filterName := d.Val()
168 moduleID := "caddy.logging.encoders.filter." + filterName
169 unm, err := caddyfile.UnmarshalModule(d, moduleID)
170 if err != nil {
171 return err
172 }
173 filter, ok := unm.(LogFieldFilter)
174 if !ok {
175 return d.Errf("module %s (%T) is not a logging.LogFieldFilter", moduleID, unm)
176 }
177
178 // Special handling for regexp filters to support multiple instances
179 if regexpFilter, isRegexp := filter.(*RegexpFilter); isRegexp {
180 regexpFilters[field] = append(regexpFilters[field], regexpFilter)
181 return nil // Don't set FieldsRaw yet, we'll merge them later
182 }
183
184 // Check if we're trying to add a non-regexp filter to a field that already has regexp filters
185 if _, hasRegexpFilters := regexpFilters[field]; hasRegexpFilters {
186 return d.Errf("cannot mix regexp filters with other filter types for field %s", field)
187 }
188
189 // Check if field already has a filter and it's not regexp-related
190 if _, exists := fe.FieldsRaw[field]; exists {
191 return d.Errf("field %s already has a filter; multiple non-regexp filters per field are not supported", field)
192 }
193
194 fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(filter, "filter", filterName, nil)
195 return nil
196 }
197
198 for d.NextBlock(0) {
199 switch d.Val() {
200 case "wrap":
201 if !d.NextArg() {
202 return d.ArgErr()
203 }
204 moduleName := d.Val()
205 moduleID := "caddy.logging.encoders." + moduleName
206 unm, err := caddyfile.UnmarshalModule(d, moduleID)
207 if err != nil {
208 return err
209 }
210 enc, ok := unm.(zapcore.Encoder)
211 if !ok {
212 return d.Errf("module %s (%T) is not a zapcore.Encoder", moduleID, unm)
213 }
214 fe.WrappedRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, nil)
215
216 case "fields":
217 for nesting := d.Nesting(); d.NextBlock(nesting); {
218 err := parseField()
219 if err != nil {
220 return err
221 }
222 }
223
224 default:
225 // if unknown, assume it's a field so that
226 // the config can be flat
227 err := parseField()
228 if err != nil {
229 return err
230 }
231 }
232 }
233
234 // After parsing all fields, merge multiple regexp filters into MultiRegexpFilter
235 for field, filters := range regexpFilters {
236 if len(filters) == 1 {
237 // Single regexp filter, use the original RegexpFilter
238 fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(filters[0], "filter", "regexp", nil)
239 } else {
240 // Multiple regexp filters, merge into MultiRegexpFilter
241 multiFilter := &MultiRegexpFilter{}
242 for _, regexpFilter := range filters {
243 err := multiFilter.AddOperation(regexpFilter.RawRegexp, regexpFilter.Value)
244 if err != nil {
245 return fmt.Errorf("adding regexp operation for field %s: %v", field, err)
246 }
247 }
248 fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(multiFilter, "filter", "multi_regexp", nil)
249 }
250 }
251
252 return nil
253 }
254
255 // AddArray is part of the zapcore.ObjectEncoder interface.
256 // Array elements do not get filtered.
257 func (fe FilterEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error {
258 if filter, ok := fe.Fields[fe.keyPrefix+key]; ok {
259 filter.Filter(zap.Array(key, marshaler)).AddTo(fe.wrapped)
260 return nil
261 }
262 return fe.wrapped.AddArray(key, marshaler)
263 }
264
265 // AddObject is part of the zapcore.ObjectEncoder interface.
266 func (fe FilterEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error {
267 if fe.filtered(key, marshaler) {
268 return nil
269 }
270 fe.keyPrefix += key + ">"
271 return fe.wrapped.AddObject(key, logObjectMarshalerWrapper{
272 enc: fe,
273 marsh: marshaler,
274 })
275 }
276
277 // AddBinary is part of the zapcore.ObjectEncoder interface.
278 func (fe FilterEncoder) AddBinary(key string, value []byte) {
279 if !fe.filtered(key, value) {
280 fe.wrapped.AddBinary(key, value)
281 }
282 }
283
284 // AddByteString is part of the zapcore.ObjectEncoder interface.
285 func (fe FilterEncoder) AddByteString(key string, value []byte) {
286 if !fe.filtered(key, value) {
287 fe.wrapped.AddByteString(key, value)
288 }
289 }
290
291 // AddBool is part of the zapcore.ObjectEncoder interface.
292 func (fe FilterEncoder) AddBool(key string, value bool) {
293 if !fe.filtered(key, value) {
294 fe.wrapped.AddBool(key, value)
295 }
296 }
297
298 // AddComplex128 is part of the zapcore.ObjectEncoder interface.
299 func (fe FilterEncoder) AddComplex128(key string, value complex128) {
300 if !fe.filtered(key, value) {
301 fe.wrapped.AddComplex128(key, value)
302 }
303 }
304
305 // AddComplex64 is part of the zapcore.ObjectEncoder interface.
306 func (fe FilterEncoder) AddComplex64(key string, value complex64) {
307 if !fe.filtered(key, value) {
308 fe.wrapped.AddComplex64(key, value)
309 }
310 }
311
312 // AddDuration is part of the zapcore.ObjectEncoder interface.
313 func (fe FilterEncoder) AddDuration(key string, value time.Duration) {
314 if !fe.filtered(key, value) {
315 fe.wrapped.AddDuration(key, value)
316 }
317 }
318
319 // AddFloat64 is part of the zapcore.ObjectEncoder interface.
320 func (fe FilterEncoder) AddFloat64(key string, value float64) {
321 if !fe.filtered(key, value) {
322 fe.wrapped.AddFloat64(key, value)
323 }
324 }
325
326 // AddFloat32 is part of the zapcore.ObjectEncoder interface.
327 func (fe FilterEncoder) AddFloat32(key string, value float32) {
328 if !fe.filtered(key, value) {
329 fe.wrapped.AddFloat32(key, value)
330 }
331 }
332
333 // AddInt is part of the zapcore.ObjectEncoder interface.
334 func (fe FilterEncoder) AddInt(key string, value int) {
335 if !fe.filtered(key, value) {
336 fe.wrapped.AddInt(key, value)
337 }
338 }
339
340 // AddInt64 is part of the zapcore.ObjectEncoder interface.
341 func (fe FilterEncoder) AddInt64(key string, value int64) {
342 if !fe.filtered(key, value) {
343 fe.wrapped.AddInt64(key, value)
344 }
345 }
346
347 // AddInt32 is part of the zapcore.ObjectEncoder interface.
348 func (fe FilterEncoder) AddInt32(key string, value int32) {
349 if !fe.filtered(key, value) {
350 fe.wrapped.AddInt32(key, value)
351 }
352 }
353
354 // AddInt16 is part of the zapcore.ObjectEncoder interface.
355 func (fe FilterEncoder) AddInt16(key string, value int16) {
356 if !fe.filtered(key, value) {
357 fe.wrapped.AddInt16(key, value)
358 }
359 }
360
361 // AddInt8 is part of the zapcore.ObjectEncoder interface.
362 func (fe FilterEncoder) AddInt8(key string, value int8) {
363 if !fe.filtered(key, value) {
364 fe.wrapped.AddInt8(key, value)
365 }
366 }
367
368 // AddString is part of the zapcore.ObjectEncoder interface.
369 func (fe FilterEncoder) AddString(key, value string) {
370 if !fe.filtered(key, value) {
371 fe.wrapped.AddString(key, value)
372 }
373 }
374
375 // AddTime is part of the zapcore.ObjectEncoder interface.
376 func (fe FilterEncoder) AddTime(key string, value time.Time) {
377 if !fe.filtered(key, value) {
378 fe.wrapped.AddTime(key, value)
379 }
380 }
381
382 // AddUint is part of the zapcore.ObjectEncoder interface.
383 func (fe FilterEncoder) AddUint(key string, value uint) {
384 if !fe.filtered(key, value) {
385 fe.wrapped.AddUint(key, value)
386 }
387 }
388
389 // AddUint64 is part of the zapcore.ObjectEncoder interface.
390 func (fe FilterEncoder) AddUint64(key string, value uint64) {
391 if !fe.filtered(key, value) {
392 fe.wrapped.AddUint64(key, value)
393 }
394 }
395
396 // AddUint32 is part of the zapcore.ObjectEncoder interface.
397 func (fe FilterEncoder) AddUint32(key string, value uint32) {
398 if !fe.filtered(key, value) {
399 fe.wrapped.AddUint32(key, value)
400 }
401 }
402
403 // AddUint16 is part of the zapcore.ObjectEncoder interface.
404 func (fe FilterEncoder) AddUint16(key string, value uint16) {
405 if !fe.filtered(key, value) {
406 fe.wrapped.AddUint16(key, value)
407 }
408 }
409
410 // AddUint8 is part of the zapcore.ObjectEncoder interface.
411 func (fe FilterEncoder) AddUint8(key string, value uint8) {
412 if !fe.filtered(key, value) {
413 fe.wrapped.AddUint8(key, value)
414 }
415 }
416
417 // AddUintptr is part of the zapcore.ObjectEncoder interface.
418 func (fe FilterEncoder) AddUintptr(key string, value uintptr) {
419 if !fe.filtered(key, value) {
420 fe.wrapped.AddUintptr(key, value)
421 }
422 }
423
424 // AddReflected is part of the zapcore.ObjectEncoder interface.
425 func (fe FilterEncoder) AddReflected(key string, value any) error {
426 if !fe.filtered(key, value) {
427 return fe.wrapped.AddReflected(key, value)
428 }
429 return nil
430 }
431
432 // OpenNamespace is part of the zapcore.ObjectEncoder interface.
433 func (fe FilterEncoder) OpenNamespace(key string) {
434 fe.wrapped.OpenNamespace(key)
435 }
436
437 // Clone is part of the zapcore.ObjectEncoder interface.
438 // We don't use it as of Oct 2019 (v2 beta 7), I'm not
439 // really sure what it'd be useful for in our case.
440 func (fe FilterEncoder) Clone() zapcore.Encoder {
441 return FilterEncoder{
442 Fields: fe.Fields,
443 wrapped: fe.wrapped.Clone(),
444 keyPrefix: fe.keyPrefix,
445 }
446 }
447
448 // EncodeEntry partially implements the zapcore.Encoder interface.
449 func (fe FilterEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
450 // without this clone and storing it to fe.wrapped, fields
451 // from subsequent log entries get appended to previous
452 // ones, and I'm not 100% sure why; see end of
453 // https://github.com/uber-go/zap/issues/750
454 fe.wrapped = fe.wrapped.Clone()
455 for _, field := range fields {
456 field.AddTo(fe)
457 }
458 return fe.wrapped.EncodeEntry(ent, nil)
459 }
460
461 // filtered returns true if the field was filtered.
462 // If true is returned, the field was filtered and
463 // added to the underlying encoder (so do not do
464 // that again). If false was returned, the field has
465 // not yet been added to the underlying encoder.
466 func (fe FilterEncoder) filtered(key string, value any) bool {
467 filter, ok := fe.Fields[fe.keyPrefix+key]
468 if !ok {
469 return false
470 }
471 filter.Filter(zap.Any(key, value)).AddTo(fe.wrapped)
472 return true
473 }
474
475 // logObjectMarshalerWrapper allows us to recursively
476 // filter fields of objects as they get encoded.
477 type logObjectMarshalerWrapper struct {
478 enc FilterEncoder
479 marsh zapcore.ObjectMarshaler
480 }
481
482 // MarshalLogObject implements the zapcore.ObjectMarshaler interface.
483 func (mom logObjectMarshalerWrapper) MarshalLogObject(_ zapcore.ObjectEncoder) error {
484 return mom.marsh.MarshalLogObject(mom.enc)
485 }
486
487 // Interface guards
488 var (
489 _ zapcore.Encoder = (*FilterEncoder)(nil)
490 _ zapcore.ObjectMarshaler = (*logObjectMarshalerWrapper)(nil)
491 _ caddyfile.Unmarshaler = (*FilterEncoder)(nil)
492 _ caddy.ConfiguresFormatterDefault = (*FilterEncoder)(nil)
493 )