telemetry

package
v0.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2026 License: GPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

Package telemetry provides OpenTelemetry instrumentation for contextd.

Package telemetry provides OpenTelemetry instrumentation for contextd.

Overview

This package implements distributed tracing and metrics collection using the OpenTelemetry Go SDK. It exports telemetry data to an OTEL Collector, which forwards to VictoriaMetrics (metrics, logs, traces).

Usage

Create telemetry instance:

cfg := telemetry.NewDefaultConfig()
tel, err := telemetry.New(ctx, cfg)
if err != nil {
    log.Fatal(err)
}
defer tel.Shutdown(ctx)

Use tracer and meter:

tracer := tel.Tracer("contextd.grpc")
ctx, span := tracer.Start(ctx, "SafeExec.Bash")
defer span.End()

meter := tel.Meter("contextd.grpc")
counter, _ := meter.Int64Counter("grpc.requests")
counter.Add(ctx, 1)

Configuration

telemetry:
  enabled: true
  endpoint: "localhost:4317"
  service_name: "contextd"
  sampling:
    rate: 1.0  # 100% in dev, lower in prod
    always_on_errors: true
  metrics:
    enabled: true
    export_interval: "15s"

Error Handling

Telemetry failures do not crash the application. If telemetry cannot be initialized, the instance degrades gracefully and returns no-op providers.

Testing

Use TestTelemetry for tests:

tt := telemetry.NewTestTelemetry()
tracer := tt.Tracer("test")
_, span := tracer.Start(ctx, "test-span")
span.End()
tt.AssertSpanExists(t, "test-span")

See CLAUDE.md for instrumentation layers and key metrics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Enabled        bool           `koanf:"enabled"`
	Endpoint       string         `koanf:"endpoint"`
	Protocol       string         `koanf:"protocol"`        // "grpc" or "http/protobuf" (default: "grpc")
	Insecure       bool           `koanf:"insecure"`        // Use insecure connection (default: true for localhost)
	TLSSkipVerify  bool           `koanf:"tls_skip_verify"` // Skip TLS certificate verification (for internal CAs)
	ServiceName    string         `koanf:"service_name"`
	ServiceVersion string         `koanf:"service_version"`
	Sampling       SamplingConfig `koanf:"sampling"`
	Metrics        MetricsConfig  `koanf:"metrics"`
	Shutdown       ShutdownConfig `koanf:"shutdown"`
}

Config holds telemetry configuration.

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig returns production-ready telemetry defaults. Telemetry is disabled by default for new users who don't have an OTEL collector. Set OTEL_ENABLE=true or configure telemetry in config.yaml to enable.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks configuration for errors.

type HealthStatus

type HealthStatus struct {
	Healthy  bool
	Degraded bool
}

Health returns the current health status.

type MeterProviderOption

type MeterProviderOption func(*meterProviderOptions)

MeterProviderOption configures MeterProvider creation.

func WithMetricExporter

func WithMetricExporter(exp metric.Exporter) MeterProviderOption

WithMetricExporter overrides the default OTLP exporter (for testing).

type MetricsConfig

type MetricsConfig struct {
	Enabled        bool            `koanf:"enabled"`
	ExportInterval config.Duration `koanf:"export_interval"`
}

MetricsConfig controls metrics export.

type SamplingConfig

type SamplingConfig struct {
	Rate           float64 `koanf:"rate"`             // 0.0-1.0, default 1.0
	AlwaysOnErrors bool    `koanf:"always_on_errors"` // Always capture error traces
}

SamplingConfig controls trace sampling behavior.

type ShutdownConfig

type ShutdownConfig struct {
	Timeout config.Duration `koanf:"timeout"`
}

ShutdownConfig controls graceful shutdown behavior.

type Telemetry

type Telemetry struct {
	// contains filtered or unexported fields
}

Telemetry provides OpenTelemetry instrumentation for contextd.

It manages TracerProvider, MeterProvider, and graceful shutdown. Telemetry failures do not crash the application; they degrade gracefully.

func New

func New(ctx context.Context, cfg *Config) (*Telemetry, error)

New creates a new Telemetry instance and initializes providers.

If telemetry is disabled in config, returns a no-op instance. Provider initialization errors are logged but don't fail; the instance degrades gracefully.

func (*Telemetry) ForceFlush

func (t *Telemetry) ForceFlush(ctx context.Context) error

ForceFlush immediately exports all pending telemetry data.

Useful for testing or before critical operations.

func (*Telemetry) Health

func (t *Telemetry) Health() HealthStatus

Health returns the current telemetry health status.

func (*Telemetry) IsEnabled

func (t *Telemetry) IsEnabled() bool

IsEnabled returns true if telemetry is enabled and healthy.

func (*Telemetry) LoggerProvider

func (t *Telemetry) LoggerProvider() log.LoggerProvider

LoggerProvider returns the log provider for OTEL logging bridge.

May return nil if not configured.

func (*Telemetry) Meter

func (t *Telemetry) Meter(name string, opts ...metric.MeterOption) metric.Meter

Meter returns a meter for the given instrumentation scope.

Returns a no-op meter if telemetry is disabled or degraded.

func (*Telemetry) SetLoggerProvider

func (t *Telemetry) SetLoggerProvider(lp log.LoggerProvider)

SetLoggerProvider sets the logger provider for OTEL logging bridge.

func (*Telemetry) Shutdown

func (t *Telemetry) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down all telemetry providers.

Should be called during application shutdown to flush pending telemetry. Uses the shutdown timeout from config.

func (*Telemetry) Tracer

func (t *Telemetry) Tracer(name string, opts ...oteltrace.TracerOption) oteltrace.Tracer

Tracer returns a tracer for the given instrumentation scope.

Returns a no-op tracer if telemetry is disabled or degraded.

type TestTelemetry

type TestTelemetry struct {
	*Telemetry

	SpanRecorder *tracetest.SpanRecorder
	MetricReader *testMetricReader
	// contains filtered or unexported fields
}

TestTelemetry provides in-memory telemetry for testing.

func NewTestTelemetry

func NewTestTelemetry() *TestTelemetry

NewTestTelemetry creates telemetry with in-memory exporters for testing.

func (*TestTelemetry) AssertSpanAttribute

func (t *TestTelemetry) AssertSpanAttribute(tb testing.TB, spanName string, key string, expected interface{})

AssertSpanAttribute verifies a span has the expected attribute.

func (*TestTelemetry) AssertSpanExists

func (t *TestTelemetry) AssertSpanExists(tb testing.TB, name string)

AssertSpanExists verifies a span with the given name was recorded.

func (*TestTelemetry) Reset

func (t *TestTelemetry) Reset()

Reset clears all recorded spans and metrics.

func (*TestTelemetry) SpanByName

func (t *TestTelemetry) SpanByName(name string) trace.ReadOnlySpan

SpanByName finds a span by name, or nil if not found.

func (*TestTelemetry) Spans

func (t *TestTelemetry) Spans() []trace.ReadOnlySpan

Spans returns all recorded spans.

type TracerProviderOption

type TracerProviderOption func(*tracerProviderOptions)

TracerProviderOption configures TracerProvider creation.

func WithTraceExporter

func WithTraceExporter(exp trace.SpanExporter) TracerProviderOption

WithTraceExporter overrides the default OTLP exporter (for testing).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL