Debian Codegraph @

service/internal/componentattribute/logger_zap.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package componentattribute // import "go.opentelemetry.io/collector/service/internal/componentattribute"
5
6 import (
7 "slices"
8
9 "go.opentelemetry.io/otel/attribute"
10 "go.uber.org/zap"
11 "go.uber.org/zap/zapcore"
12
13 "go.opentelemetry.io/collector/internal/telemetry"
14 )
15
16 // This wrapper around zapcore.Field tells the Zap -> OTel bridge that the field
17 // should be turned into an instrumentation scope instead of a set of log record attributes.
18 type scopeAttributesField struct {
19 fields []zapcore.Field
20 attrs []attribute.KeyValue
21 }
22
23 var _ zapcore.ObjectMarshaler = scopeAttributesField{}
24
25 func (saf scopeAttributesField) MarshalLogObject(enc zapcore.ObjectEncoder) error {
26 for _, field := range saf.fields {
27 field.AddTo(enc)
28 }
29 return nil
30 }
31
32 func makeScopeField(attrs []attribute.KeyValue) zap.Field {
33 return zap.Inline(scopeAttributesField{
34 fields: telemetry.ToZapFields(attrs),
35 attrs: attrs,
36 })
37 }
38
39 func ExtractLogScopeAttributes(field zap.Field) ([]attribute.KeyValue, bool) {
40 if field.Type != zapcore.InlineMarshalerType {
41 return nil, false
42 }
43 saf, ok := field.Interface.(scopeAttributesField)
44 if !ok {
45 return nil, false
46 }
47 return saf.attrs, true
48 }
49
50 type coreWithAttributes struct {
51 zapcore.Core
52 sourceCore zapcore.Core
53 attrs []attribute.KeyValue
54 withFields []zap.Field
55 }
56
57 var _ zapcore.Core = coreWithAttributes{}
58
59 func (cwa coreWithAttributes) With(fields []zapcore.Field) zapcore.Core {
60 cwa.withFields = append(cwa.withFields, fields...)
61 cwa.Core = cwa.Core.With(fields)
62 return cwa
63 }
64
65 func LoggerWithAttributes(logger *zap.Logger, attrs []attribute.KeyValue) *zap.Logger {
66 return logger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {
67 return coreWithAttributes{
68 Core: c.With([]zap.Field{makeScopeField(attrs)}),
69 sourceCore: c,
70 attrs: attrs,
71 }
72 }))
73 }
74
75 func (cwa coreWithAttributes) DropInjectedAttributes(droppedAttrs ...string) zapcore.Core {
76 cwa.attrs = slices.DeleteFunc(slices.Clone(cwa.attrs), func(kv attribute.KeyValue) bool {
77 return slices.Contains(droppedAttrs, string(kv.Key))
78 })
79 cwa.Core = cwa.sourceCore.With(append([]zap.Field{makeScopeField(cwa.attrs)}, cwa.withFields...))
80 return cwa
81 }