|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package componentattribute_test |
| 5 | + |
| 6 | +import ( |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + "go.opentelemetry.io/otel/attribute" |
| 11 | + "go.uber.org/zap" |
| 12 | + "go.uber.org/zap/zapcore" |
| 13 | + "go.uber.org/zap/zaptest/observer" |
| 14 | + |
| 15 | + "go.opentelemetry.io/collector/component/componentattribute" |
| 16 | + "go.opentelemetry.io/collector/pipeline" |
| 17 | +) |
| 18 | + |
| 19 | +type loggerCore interface { |
| 20 | + Without(fields ...string) zapcore.Core |
| 21 | +} |
| 22 | + |
| 23 | +func TestCore(t *testing.T) { |
| 24 | + core, observed := observer.New(zap.DebugLevel) |
| 25 | + logger := zap.New(core).With(zap.String("preexisting", "value")) |
| 26 | + |
| 27 | + attrs := attribute.NewSet( |
| 28 | + attribute.String(componentattribute.SignalKey, pipeline.SignalLogs.String()), |
| 29 | + attribute.String(componentattribute.ComponentIDKey, "filelog"), |
| 30 | + ) |
| 31 | + |
| 32 | + parent := componentattribute.NewLogger(logger, &attrs) |
| 33 | + parent.Info("test parent before child") |
| 34 | + childCore := parent.Core().(loggerCore).Without(string(componentattribute.SignalKey)) |
| 35 | + child := zap.New(childCore) |
| 36 | + child.Info("test child") |
| 37 | + parent.Info("test parent after child") |
| 38 | + |
| 39 | + observedLogs := observed.All() |
| 40 | + require.Len(t, observedLogs, 3) |
| 41 | + |
| 42 | + parentContext := map[string]string{ |
| 43 | + "preexisting": "value", |
| 44 | + componentattribute.SignalKey: pipeline.SignalLogs.String(), |
| 45 | + componentattribute.ComponentIDKey: "filelog", |
| 46 | + } |
| 47 | + childContext := map[string]string{ |
| 48 | + "preexisting": "value", |
| 49 | + componentattribute.ComponentIDKey: "filelog", |
| 50 | + } |
| 51 | + |
| 52 | + require.Equal(t, "test parent before child", observedLogs[0].Message) |
| 53 | + require.Len(t, observedLogs[0].Context, len(parentContext)) |
| 54 | + for _, field := range observedLogs[0].Context { |
| 55 | + require.Equal(t, parentContext[field.Key], field.String) |
| 56 | + } |
| 57 | + |
| 58 | + require.Equal(t, "test child", observedLogs[1].Message) |
| 59 | + require.Len(t, observedLogs[1].Context, len(childContext)) |
| 60 | + for _, field := range observedLogs[1].Context { |
| 61 | + require.Equal(t, childContext[field.Key], field.String) |
| 62 | + } |
| 63 | + |
| 64 | + require.Equal(t, "test parent after child", observedLogs[2].Message) |
| 65 | + require.Len(t, observedLogs[2].Context, len(parentContext)) |
| 66 | + for _, field := range observedLogs[2].Context { |
| 67 | + require.Equal(t, parentContext[field.Key], field.String) |
| 68 | + } |
| 69 | +} |
0 commit comments