본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

커넥터 만들기 (Build a connector)

원문 보기 위키 갱신

이 페이지의 내용은 이미 어떤 종류의 추적(tracing) 텔레메트리 데이터를 생성하는 계측된 애플리케이션을 가지고 있고, OpenTelemetry Collector에 대한 이해가 있는 경우에 가장 적합해요.

출처: 문서

본문

OpenTelemetry의 커넥터 (Connectors in OpenTelemetry)

이 페이지의 내용은 이미 어떤 종류의 추적 텔레메트리 데이터를 생성하는 계측된 애플리케이션을 가지고 있고, OpenTelemetry Collector에 대한 이해가 있는 경우에 가장 적합해요.

커넥터란 무엇인가요? (What is a Connector?)

커넥터는 서로 다른 Collector 파이프라인을 연결해 그 사이에서 텔레메트리 데이터를 보내는 수단으로 작동해요. 커넥터는 한 파이프라인에는 내보내기(export)로, 다른 파이프라인에는 수신기(receiver)로 작동해요. OpenTelemetry Collector의 각 파이프라인은 한 가지 유형의 텔레메트리 데이터를 다뤄요. 한 형태의 텔레메트리 데이터를 다른 형태로 처리해야 할 필요가 있을 수 있는데, 그에 해당하는 데이터를 올바른 Collector 파이프라인으로 라우팅해야 해요.

커넥터를 사용하는 이유는 무엇인가요? (Why use a Connector?)

커넥터는 데이터 스트림을 병합, 라우팅, 복제하는 데 유용해요. 파이프라인을 서로 연결하는 순차적 파이프라이닝과 함께, 커넥터 컴포넌트는 조건부 데이터 흐름과 생성 데이터 스트림이 가능해요. 조건부 데이터 흐름은 데이터를 최우선 순위 파이프라인으로 보내고, 필요한 경우 대체 파이프라인으로 라우팅하는 오류 감지를 갖는 것을 뜻해요. 생성 데이터 스트림은 컴포넌트가 수신한 데이터를 기반으로 자신의 데이터를 생성하고 내보내는 것을 뜻해요. 이 튜토리얼은 커넥터가 파이프라인을 연결하는 능력에 초점을 맞춰요.

OpenTelemetry에는 한 유형의 텔레메트리 데이터를 다른 유형으로 변환하는 프로세서가 있어요. 몇 가지 예로 spanmetrics 프로세서와 servicegraph 프로세서가 있어요. spanmetrics 프로세서는 span 데이터에서 집계된 요청, 오류, 지속 시간 메트릭을 생성해요. servicegraph 프로세서는 trace 데이터를 분석해 서비스 간의 관계를 설명하는 메트릭을 생성해요. 이 두 프로세서 모두 trace 데이터를 받아 메트릭 데이터로 변환해요. OpenTelemetry Collector의 파이프라인은 한 유형의 데이터만 다루므로, traces 파이프라인의 프로세서에서 변환된 trace 데이터를 metrics 파이프라인으로 보내는 것이 필요해요. 역사적으로 일부 프로세서는 프로세서가 처리 후 데이터를 직접 내보내는 나쁜 관행을 따르는 우회 방법을 사용해 데이터를 전송했어요. 커넥터 컴포넌트는 이 우회 방법의 필요성을 해결했고, 우회 방법을 사용하던 프로세서들은 폐기(deprecated)되었어요. 마찬가지로 앞서 언급한 프로세서들도 최근 릴리스에서 폐기되고 커넥터로 대체되었어요.

커넥터의 전체 기능에 대한 추가 세부 사항은 다음 링크에서 확인할 수 있어요: What are Connectors in OpenTelemetry?, OpenTelemetry Connector Configurations

이전 아키텍처 (The Old Architecture):

커넥터를 사용하는 새 아키텍처 (New Architecture Using a Connector):

예시 커넥터 만들기 (Building Example Connector)

이 튜토리얼에서는 OpenTelemetry에서 커넥터 컴포넌트가 어떻게 작동하는지에 대한 기본 예시로, trace를 받아 메트릭으로 변환하는 예시 커넥터를 작성할 거예요. 기본 커넥터의 기능은 특정 속성 이름을 포함하는 trace의 span 수를 세는 것이에요. 이러한 발생 횟수는 커넥터에 저장돼요.

구성 (Configurations)

Collector 구성 설정하기 (Setting up Collector Config):

OpenTelemetry Collector에 사용할 구성을 config.yaml 파일에 설정해요. 이 파일은 데이터가 어떻게 라우팅, 처리, 내보내기될지 정의해요. 파일에 정의된 구성은 데이터 파이프라인이 어떻게 동작하길 원하는지 상세히 나타내요. 컴포넌트를 정의하고 데이터가 정의된 파이프라인을 처음부터 끝까지 어떻게 이동하는지 정의할 수 있어요. Collector 구성 방법에 대한 자세한 내용은 Collector Configurations를 참고하세요.

우리가 만들 예시 커넥터에 다음 코드를 사용해요. 이 코드는 기본적으로 유효한 OpenTelemetry Collector 구성 파일의 예시예요.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

exporters:
  debug:

connectors:
  example:

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [example]
    metrics:
      receivers: [example]
      exporters: [debug]

위 코드의 connectors 부분에서 파이프라인에 사용할 수 있는 커넥터의 이름을 선언해야 해요. 여기서 example은 이 튜토리얼에서 만들 커넥터의 이름이에요.

구현 (Implementation)

  • 예시 커넥터용 폴더를 만들어요. 이 튜토리얼에서는 exampleconnector라는 폴더를 만들 거예요.

  • 폴더로 이동해 다음을 실행해요.

go mod init github.com/gord02/exampleconnector
  • go mod tidy를 실행해요.

이렇게 하면 go.mod와 go.sum 파일이 생성돼요.

  • 폴더에 다음 파일들을 만들어요.

  • config.go - 커넥터의 설정을 정의하는 파일

  • factory.go - 커넥터의 인스턴스를 만드는 파일

config.go에서 커넥터 설정 만들기 (Create your connector settings in config.go)

인스턴스화되어 파이프라인에 참여하려면 Collector가 커넥터를 식별하고 구성 파일에서 그 설정을 올바르게 로드해야 해요.

커넥터에 설정에 대한 접근을 제공하려면 Config 구조체를 만들어요. 이 구조체는 커넥터의 각 설정에 대해 내보낸(exported) 필드를 가져야 해요. 추가된 매개변수 필드는 config.yaml 파일에서 접근할 수 있어요. 구성 파일에서의 이름은 구조체 태그를 통해 설정돼요. 구조체를 만들고 매개변수를 추가하세요. 선택적으로 주어진 기본값이 커넥터 인스턴스에 유효한지 확인하는 검증(validator) 함수를 추가할 수 있어요.

config.go 파일은 다음과 같아야 해요.

exampleconnector/config.go

package exampleconnector

import "fmt"

// Config represents the connector config settings within the collector's config.yaml
type Config struct {
    AttributeName string `mapstructure:"attribute_name"`
}

func (c *Config) Validate() error {
    if c.AttributeName == "" {
        return fmt.Errorf("attribute_name must not be empty")
    }
    return nil
}

mapstructure에 대한 자세한 내용은 Go mapstructure를 참고하세요.

팩토리 구현하기 (Implement the Factory)

객체를 인스턴스화하려면 각 컴포넌트와 연관된 NewFactory 함수를 사용해야 해요. 우리는 connector.NewFactory 함수를 사용할 거예요. connector.NewFactory 함수는 connector.Factory를 인스턴스화해 반환하며 다음 매개변수가 필요해요.

  • component.Type: 같은 유형의 모든 Collector 컴포넌트에서 커넥터를 식별하는 고유한 문자열 식별자예요. 이 문자열은 커넥터를 참조하는 이름으로도 작동해요.

  • component.CreateDefaultConfigFunc: 커넥터의 기본 component.Config 인스턴스를 반환하는 함수에 대한 참조예요.

  • ...FactoryOption: connector.FactoryOptions의 슬라이스는 커넥터가 처리할 수 있는 신호 유형을 결정해요.

  • factory.go 파일을 만들고 커넥터를 식별하는 고유 문자열을 전역 상수로 정의해요.

const defaultVal string = "request.n"

// Type is the component type name for this connector
var Type = component.MustNewType("example")
  • 기본 구성 함수를 만들어요. 커넥터 객체를 기본값으로 초기화하는 방법을 이렇게 선택해요.
func createDefaultConfig() component.Config {
    return &Config{
        AttributeName: defaultVal,
    }
}
  • 작업할 커넥터의 유형을 정의해요. 이 값은 팩토리 옵션으로 전달돼요. 커넥터는 서로 다르거나 유사한 유형의 파이프라인을 연결할 수 있어요. 커넥터의 내보내기 끝과 수신기 끝의 유형을 정의해야 해요. traces를 내보내고 metrics를 받는 커넥터는 커넥터 컴포넌트의 한 가지 뚜렷한 구성일 뿐이며, 그 정의 순서가 중요해요. traces를 내보내고 metrics를 받는 커넥터는 metrics를 내보내고 traces를 받는 커넥터와 같지 않아요.
// createTracesToMetricsConnector defines the consumer type of the connector
// We want to consume traces and export metrics, therefore, define nextConsumer as metrics, since consumer is the next component in the pipeline
func createTracesToMetricsConnector(ctx context.Context, params connector.Settings, cfg component.Config, nextConsumer consumer.Metrics) (connector.Traces, error) {
    return newConnector(params.Logger, cfg, nextConsumer)
}

createTracesToMetricsConnector는 커넥터가 데이터를 전송한 후 데이터를 받아들일 다음 컴포넌트인 소비자(consumer) 컴포넌트를 정의해 커넥터 컴포넌트를 추가로 초기화하는 함수예요. 커넥터가 여기처럼 한 가지 순서 조합만으로 제한되는 것은 아니라는 점에 유의하세요. 예를 들어 count 커넥터는 traces에서 metrics, logs에서 metrics, metrics에서 metrics로 가는 여러 함수를 정의해요.

createTracesToMetricsConnector의 매개변수:

  • context.Context: trace 수신기가 실행 컨텍스트를 올바르게 관리할 수 있도록 Collector의 context.Context에 대한 참조예요.

  • connector.CreateSettings: 수신기가 생성되는 Collector의 일부 설정에 대한 참조예요.

  • component.Config: Collector가 팩토리에 전달하는 수신기 구성 설정에 대한 참조로, Collector 구성에서 설정을 올바르게 읽을 수 있게 해줘요.

  • consumer.Metrics: 수신된 traces가 갈 파이프라인의 다음 소비자 유형에 대한 참조예요. 이것은 프로세서, 내보내기, 또는 다른 커넥터일 수 있어요.

  • 커넥터(컴포넌트)를 위한 커스텀 팩토리를 인스턴스화하는 NewFactory 함수를 작성해요.

// NewFactory creates a factory for example connector.
func NewFactory() connector.Factory {
    // OpenTelemetry connector factory to make a factory for connectors
    return connector.NewFactory(
        Type,
        createDefaultConfig,
        connector.WithTracesToMetrics(createTracesToMetricsConnector, component.StabilityLevelAlpha))
}

커넥터가 여러 가지 순서 조합의 데이터 유형을 지원할 수 있다는 점에 유의하세요.

완성되면 factory.go는 다음과 같아요.

package exampleconnector

import (
	"context"

	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/connector"
	"go.opentelemetry.io/collector/consumer"
)

const defaultVal string = "request.n"

// Type is the component type name for this connector
var Type = component.MustNewType("example")

// NewFactory creates a factory for example connector.
func NewFactory() connector.Factory {
	// OpenTelemetry connector factory to make a factory for connectors
	return connector.NewFactory(
		Type,
		createDefaultConfig,
		connector.WithTracesToMetrics(createTracesToMetricsConnector, component.StabilityLevelAlpha))
}

func createDefaultConfig() component.Config {
	return &Config{
		AttributeName: defaultVal,
	}
}

// createTracesToMetricsConnector defines the consumer type of the connector
// We want to consume traces and export metrics, therefore, define nextConsumer as metrics, since consumer is the next component in the pipeline
func createTracesToMetricsConnector(ctx context.Context, params connector.Settings, cfg component.Config, nextConsumer consumer.Metrics) (connector.Traces, error) {
	return newConnector(params.Logger, cfg, nextConsumer)
}

Trace 커넥터 구현하기 (Implementing the Trace Connector)

connector.go 파일에서 컴포넌트 유형에 특화된 인터페이스의 메서드를 구현해요. 이 튜토리얼에서는 Traces 커넥터를 구현하므로 baseConsumer, Traces, component.Component 인터페이스를 구현해야 해요.

  • 커넥터에 원하는 매개변수로 커넥터 구조체를 정의해요.
// schema for connector
type connectorImp struct {
    config          Config
    metricsConsumer consumer.Metrics
    logger          *zap.Logger
    // Include these parameters if a specific implementation for the Start and Shutdown function are not needed
    component.StartFunc
    component.ShutdownFunc
}
  • 커넥터를 만들기 위한 newConnector 함수를 정의해요.
// newConnector is a function to create a new connector
func newConnector(logger *zap.Logger, config component.Config, nextConsumer consumer.Metrics) (*connectorImp, error) {
    logger.Info("Building exampleconnector connector")
    cfg := config.(*Config)

    return &connectorImp{
        config:          *cfg,
        logger:          logger,
        metricsConsumer: nextConsumer,
    }, nil
}

newConnector 함수는 커넥터 인스턴스를 만드는 팩토리 함수예요.

  • 인터페이스를 올바르게 구현하기 위해 Capabilities 메서드를 구현해요.
// Capabilities implements the consumer interface.
func (c *connectorImp) Capabilities() consumer.Capabilities {
    return consumer.Capabilities{MutatesData: false}
}

커넥터가 consumer 유형인지 확인하려면 Capabilities 메서드를 구현해요. 이 메서드는 컴포넌트가 데이터를 변조할 수 있는지 여부 같은 컴포넌트의 기능을 정의해요. MutatesData가 true로 설정되면 커넥터가 전달받은 데이터 구조를 변조한다는 뜻이에요.

  • 텔레메트리 데이터를 소비하도록 Consumer 메서드를 구현해요.
// ConsumeTraces method is called for each instance of a trace sent to the connector
func (c *connectorImp) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {
    // loop through the levels of spans of the one trace consumed
    for i := 0; i < td.ResourceSpans().Len(); i++ {
        resourceSpan := td.ResourceSpans().At(i)

        for j := 0; j < resourceSpan.ScopeSpans().Len(); j++ {
            scopeSpan := resourceSpan.ScopeSpans().At(j)

            for k := 0; k < scopeSpan.Spans().Len(); k++ {
                span := scopeSpan.Spans().At(k)
                attrs := span.Attributes()
                if _, ok := attrs.Get(c.config.AttributeName); ok {
                    // create metric only if span of trace had the specific attribute
                    metrics := pmetric.NewMetrics()
                    return c.metricsConsumer.ConsumeMetrics(ctx, metrics)
                }
            }
        }
    }
    return nil
}
  • 선택 사항: 특정 구현이 필요한 경우에만 인터페이스를 올바르게 구현하기 위해 Start와 Shutdown 메서드를 구현해요. 그렇지 않으면 정의된 커넥터 구조체의 일부로 component.StartFunc와 component.ShutdownFunc를 포함하는 것으로 충분해요.

완성된 커넥터 파일은 다음과 같아야 해요.

exampleconnector/connector.go

package exampleconnector

import (
	"context"

	"go.uber.org/zap"

	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/consumer"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.opentelemetry.io/collector/pdata/ptrace"
)

// schema for connector
type connectorImp struct {
	config          Config
	metricsConsumer consumer.Metrics
	logger          *zap.Logger
	// Include these parameters if a specific implementation for the Start and Shutdown function are not needed
	component.StartFunc
	component.ShutdownFunc
}

// newConnector is a function to create a new connector
func newConnector(logger *zap.Logger, config component.Config, nextConsumer consumer.Metrics) (*connectorImp, error) {
	logger.Info("Building exampleconnector connector")
	cfg := config.(*Config)

	return &connectorImp{
		config:          *cfg,
		logger:          logger,
		metricsConsumer: nextConsumer,
	}, nil
}

// Capabilities implements the consumer interface.
func (c *connectorImp) Capabilities() consumer.Capabilities {
	return consumer.Capabilities{MutatesData: false}
}

// ConsumeTraces method is called for each instance of a trace sent to the connector
func (c *connectorImp) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {
	// loop through the levels of spans of the one trace consumed
	for i := 0; i < td.ResourceSpans().Len(); i++ {
		resourceSpan := td.ResourceSpans().At(i)

		for j := 0; j < resourceSpan.ScopeSpans().Len(); j++ {
			scopeSpan := resourceSpan.ScopeSpans().At(j)

			for k := 0; k < scopeSpan.Spans().Len(); k++ {
				span := scopeSpan.Spans().At(k)
				attrs := span.Attributes()
				if _, ok := attrs.Get(c.config.AttributeName); ok {
					// create metric only if span of trace had the specific attribute
					metrics := pmetric.NewMetrics()
					return c.metricsConsumer.ConsumeMetrics(ctx, metrics)
				}
			}
		}
	}
	return nil
}

컴포넌트 사용하기 (Using the Component)

OpenTelemetry Collector Builder 사용 요약 (Summary of Using OpenTelemetry Collector Builder):

OpenTelemetry Collector Builder를 사용해 코드를 빌드하고 실행할 수 있어요. Collector Builder는 자신만의 OpenTelemetry Collector 바이너리를 빌드할 수 있게 해주는 도구예요. 필요에 따라 컴포넌트(수신기, 프로세서, 커넥터, 내보내기)를 추가하거나 제거할 수 있어요.

  • OpenTelemetry Collector Builder 설치 지침을 따르세요.

  • 구성 파일을 작성해요.

설치가 끝나면 다음 단계는 구성 파일 builder-config.yaml을 만드는 거예요. 이 파일은 커스텀 바이너리에 포함할 Collector 컴포넌트를 정의해요.

새 커넥터 컴포넌트를 포함해 사용할 수 있는 구성 파일의 예시는 다음과 같아요.

dist:
  name: otelcol-dev-bin
  description: Basic OpenTelemetry collector distribution for Developers
  output_path: ./otelcol-dev

exporters:
  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.129.0

receivers:
  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.129.0

# Not used in this tutorial, but can be added if needed for your use case
# processors:

connectors:
  - gomod: github.com/gord02/exampleconnector v0.129.0

replaces:
  # a list of "replaces" directives that will be part of the resulting go.mod

  # This replace statement is necessary since the newly added component is not found/published to GitHub yet. Replace references to GitHub path with the local path
  - github.com/gord02/exampleconnector =>
    [PATH-TO-COMPONENT-CODE]/exampleconnector

replace 문을 포함하는 것이 필요해요. 새로 만든 컴포넌트가 아직 GitHub에 게시되지 않았기 때문이에요. 컴포넌트에 대한 GitHub 경로 참조를 코드의 로컬 경로로 바꿔야 해요.

Go에서 교체에 대한 자세한 내용은 Go mod file Replace를 참고하세요.

  • Collector 바이너리를 빌드해요.

포함된 커넥터 컴포넌트를 상세히 나타내는 빌더 구성 파일을 전달하며 빌더를 실행하면 커스텀 Collector 바이너리가 빌드돼요.

./ocb --config [PATH-TO-CONFIG]/builder-config.yaml

이렇게 하면 구성 파일에 있던 지정된 출력 경로 디렉터리에 Collector 바이너리가 생성돼요.

빌드에 성공하면 다음과 유사한 출력이 보일 거예요.

./ocb --config builder-config.yaml
2025-07-15T22:10:10.351+0900    INFO    internal/command.go:99  OpenTelemetry Collector Builder {"version": "0.129.0"}
2025-07-15T22:10:10.352+0900    INFO    internal/command.go:104 Using config file       {"path": "builder-config.yaml"}
2025-07-15T22:10:10.353+0900    INFO    builder/config.go:160   Using go        {"go-executable": "/opt/homebrew/Cellar/go@1.23/1.23.6/bin/go"}
2025-07-15T22:10:10.354+0900    INFO    builder/main.go:99      Sources created {"path": "./otelcol-dev"}
2025-07-15T22:10:10.516+0900    INFO    builder/main.go:201     Getting go modules
2025-07-15T22:10:10.554+0900    INFO    builder/main.go:110     Compiling
2025-07-15T22:10:13.369+0900    INFO    builder/main.go:140     Compiled        {"binary": "./otelcol-dev/otelcol-dev-bin"}
  • Collector 바이너리를 실행해요.

이제 3단계 출력의 바이너리 경로(예: {"binary": "./otelcol-dev/otelcol-dev-bin"})를 사용해 커스텀 Collector 바이너리를 실행할 수 있어요.

./otelcol-dev/otelcol-dev-bin --config [PATH-TO-CONFIG]/config.yaml

출력 경로 이름과 dist의 이름은 build-config.yaml에 상세히 나와 있어요.

커넥터 테스트하기 (Testing Your Connector)

예시 커넥터를 빌드했으니 이제 단위 테스트로 그 기능을 검증해 보아요. Go 단위 테스트는 더 나은 커버리지를 제공하고 유지 관리하기 쉬워요.

단위 테스트 작성하기 (Writing Unit Tests)

커넥터 디렉터리에 테스트 파일 connector_test.go를 만들어요.

exampleconnector/connector_test.go

package exampleconnector

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/vibeus/opentelemetry-collector/confmap/xconfmap"
	"go.opentelemetry.io/collector/consumer/consumertest"
	"go.opentelemetry.io/collector/pdata/ptrace"
	"go.uber.org/zap"
)

func TestConsumeTraces(t *testing.T) {
	// Create a test consumer that captures metrics
	metricsConsumer := &consumertest.MetricsSink{}

	// Create connector with test configuration
	cfg := &Config{
		AttributeName: "request.n",
	}

	connector, err := newConnector(zap.NewNop(), cfg, metricsConsumer)
	require.NoError(t, err)

	ctx := context.Background()

	t.Run("span with target attribute generates metric", func(t *testing.T) {
		// Reset the consumer
		metricsConsumer.Reset()

		// Create trace data with target attribute
		traces := ptrace.NewTraces()
		resourceSpan := traces.ResourceSpans().AppendEmpty()
		scopeSpan := resourceSpan.ScopeSpans().AppendEmpty()
		span := scopeSpan.Spans().AppendEmpty()

		// Add the target attribute
		span.Attributes().PutStr("request.n", "test-value")
		span.Attributes().PutStr("http.method", "GET")

		// Consume the traces
		err := connector.ConsumeTraces(ctx, traces)
		require.NoError(t, err)

		// Verify metric was generated
		assert.Equal(t, 1, len(metricsConsumer.AllMetrics()))
	})

	t.Run("span without target attribute does not generate metric", func(t *testing.T) {
		// Reset the consumer
		metricsConsumer.Reset()

		// Create trace data without target attribute
		traces := ptrace.NewTraces()
		resourceSpan := traces.ResourceSpans().AppendEmpty()
		scopeSpan := resourceSpan.ScopeSpans().AppendEmpty()
		span := scopeSpan.Spans().AppendEmpty()

		// Add other attributes but not the target one
		span.Attributes().PutStr("http.method", "POST")
		span.Attributes().PutStr("user.id", "12345")

		// Consume the traces
		err := connector.ConsumeTraces(ctx, traces)
		require.NoError(t, err)

		// Verify no metric was generated
		assert.Equal(t, 0, len(metricsConsumer.AllMetrics()))
	})

	t.Run("multiple spans with mixed attributes", func(t *testing.T) {
		// Reset the consumer
		metricsConsumer.Reset()

		// Create trace data with multiple spans
		traces := ptrace.NewTraces()
		resourceSpan := traces.ResourceSpans().AppendEmpty()
		scopeSpan := resourceSpan.ScopeSpans().AppendEmpty()

		// First span with target attribute
		span1 := scopeSpan.Spans().AppendEmpty()
		span1.Attributes().PutStr("request.n", "value1")

		// Second span without target attribute
		span2 := scopeSpan.Spans().AppendEmpty()
		span2.Attributes().PutStr("other.attr", "value2")

		// Consume the traces
		err := connector.ConsumeTraces(ctx, traces)
		require.NoError(t, err)

		// Should generate exactly one metric (from first span only)
		assert.Equal(t, 1, len(metricsConsumer.AllMetrics()))
	})
}

func TestConnectorCapabilities(t *testing.T) {
	connector := &connectorImp{}
	capabilities := connector.Capabilities()
	assert.False(t, capabilities.MutatesData)
}

func TestCreateDefaultConfig(t *testing.T) {
	cfg := createDefaultConfig()
	assert.NotNil(t, cfg)

	exampleConfig := cfg.(*Config)
	assert.Equal(t, "request.n", exampleConfig.AttributeName)
}

func TestConfigValidation(t *testing.T) {
	t.Run("valid config", func(t *testing.T) {
		cfg := &Config{
			AttributeName: "test.attribute",
		}
		err := xconfmap.Validate(cfg)
		assert.NoError(t, err)
	})

	t.Run("invalid config - empty attribute name", func(t *testing.T) {
		cfg := &Config{
			AttributeName: "",
		}
		err := xconfmap.Validate(cfg)
		assert.Error(t, err)
		assert.Contains(t, err.Error(), "attribute_name must not be empty")
	})
}

테스트 실행하기 (Running the Tests)

  • go.mod에 테스트 의존성을 추가해요.
go mod tidy
  • 테스트를 실행해요.
go test -cover -v ./...

예상 테스트 출력 (Expected Test Output)

테스트가 성공적으로 실행되면 다음과 유사한 출력이 보일 거예요.

go test -cover -v ./...
=== RUN   TestConsumeTraces
=== RUN   TestConsumeTraces/span_with_target_attribute_generates_metric
=== RUN   TestConsumeTraces/span_without_target_attribute_does_not_generate_metric
=== RUN   TestConsumeTraces/multiple_spans_with_mixed_attributes
--- PASS: TestConsumeTraces (0.00s)
    --- PASS: TestConsumeTraces/span_with_target_attribute_generates_metric (0.00s)
    --- PASS: TestConsumeTraces/span_without_target_attribute_does_not_generate_metric (0.00s)
    --- PASS: TestConsumeTraces/multiple_spans_with_mixed_attributes (0.00s)
=== RUN   TestConnectorCapabilities
--- PASS: TestConnectorCapabilities (0.00s)
=== RUN   TestCreateDefaultConfig
--- PASS: TestCreateDefaultConfig (0.00s)
=== RUN   TestConfigValidation
=== RUN   TestConfigValidation/valid_config
=== RUN   TestConfigValidation/invalid_config_-_empty_attribute_name
--- PASS: TestConfigValidation (0.00s)
    --- PASS: TestConfigValidation/valid_config (0.00s)
    --- PASS: TestConfigValidation/invalid_config_-_empty_attribute_name (0.00s)
PASS
coverage: 90.5% of statements
ok      github.com/gord02/exampleconnector      0.501s  coverage: 90.5% of statements

이 단위 테스트들은 커넥터 기능의 폭넓은 커버리지를 제공하며, OpenTelemetry Collector 생태계에서 컴포넌트 동작을 검증하는 권장 방식이에요.

OpenTelemetry Collector Builder에 대한 추가 자료:

  • Build a custom Collector
  • OpenTelemetry Collector Builder README
  • Connected Observability Pipelines in the OpenTelemetry Collector by Dan Jaglowski
  • Connector README

더 알아보기 (Learn more)