otel

package
v0.0.0-...-c9e7dd3 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package otel provides utilities for initializing and configuring OpenTelemetry. Based off of https://github.com/dagger/dagger/tree/main/sdk/go/telemetry.

Index

Examples

Constants

View Source
const NearlyImmediate = 100 * time.Millisecond

NearlyImmediate is 100ms, below which has diminishing returns in terms of visual perception vs. performance cost.

Variables

View Source
var Resource *resource.Resource

Resource is the globally configured resource, allowing it to be provided to dynamically allocated log/trace providers at runtime.

Functions

func ConfiguredLogExporter

func ConfiguredLogExporter(ctx context.Context) (sdklog.Exporter, error)

ConfiguredLogExporter examines environment variables to build a sdklog.Exporter.

func ConfiguredMetricExporter

func ConfiguredMetricExporter(ctx context.Context) (sdkmetric.Exporter, error)

ConfiguredMetricExporter examines environment variables to build a sdkmetric.Exporter.

func ConfiguredSpanExporter

func ConfiguredSpanExporter(ctx context.Context) (sdktrace.SpanExporter, error)

ConfiguredSpanExporter examines environment variables to build a sdktrace.SpanExporter.

func RunWithContext

func RunWithContext(ctx context.Context, cmd *cobra.Command, cfg *Config, verbosityEnvName string) error

RunWithContext will run the root level cobra command, with the provided OpenTelemetry configuration. It calls cfg.Init and cfg.Close appropriately.

Types

type Config

type Config struct {
	// Override auto-detect exporters from OTEL_* env variables.
	DisableEnvConfiguration bool

	// SpanProcessors are processors to prepend to the telemetry pipeline.
	SpanProcessors []sdktrace.SpanProcessor

	// BatchedTraceExporters are exporters that receive spans in batches, after
	// the spans have ended.
	BatchedTraceExporters []sdktrace.SpanExporter

	// LiveTraceExporters are exporters that can receive updates for spans at
	// runtime, rather than waiting until the span ends.
	LiveTraceExporters []sdktrace.SpanExporter

	// LogProcessors are processors to prepend to the telemetry pipeline.
	LogProcessors []sdklog.Processor

	// BatchedLogExporters are exporters that receive logs in batches.
	BatchedLogExporters []sdklog.Exporter

	// LiveLogExporters are exporters that receive logs in batches of ~100ms.
	LiveLogExporters []sdklog.Exporter

	// MetricReaders are readers that collect metric data.
	MetricReaders []sdkmetric.Reader

	// LiveMetricExporters are exporters that receive metrics in batches of ~1s.
	LiveMetricExporters []sdkmetric.Exporter

	// BatchedMetricExporters are exporters that receive metrics in batches.
	BatchedMetricExporters []sdkmetric.Exporter

	// Resource is the resource describing this component and runtime
	// environment.
	Resource *resource.Resource
	// contains filtered or unexported fields
}

Config configures the initialization of OpenTelemetry.

Example (Logs)

ExampleConfig_logs demonstrates configuration setup for exporting logs, bridged with slog, in batches.

ctx := context.Background()

rsrc, err := resource.New(ctx,
	resource.WithTelemetrySDK(),
	resource.WithAttributes(
		semconv.ServiceName("example.service"),
		semconv.ServiceVersion(fmt.Sprintf("%d.%d.%d", 0, 0, 1)),
	),
)
if err != nil {
	panic(fmt.Sprintf("insufficient resource information: error = %v", err))
}

exp, err := otlploghttp.New(ctx)
if err != nil {
	panic(fmt.Sprintf("initializing log exporter: error = %v", err))
}

cfg := Config{
	// LiveLogExporters: []sdklog.Exporter{exp}, // export every 100ms.
	BatchedLogExporters: []sdklog.Exporter{exp}, // export in batches.
	Resource:            rsrc,
}

ctx, err = cfg.Init(ctx)
if err != nil {
	panic(fmt.Sprintf("initializing OpenTelemetry: error = %v", err))
}
defer cfg.Shutdown(ctx) // ensure to shutdown, flushing remaining data to exporters

// Multi-logger setup is handled by otel.RunWithContext.
level := new(slog.LevelVar)
level.Set(slog.LevelDebug)
stdErrHandler := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})
otelHandler := otelslog.NewHandler("Example", otelslog.WithLoggerProvider(cfg.logProvider))
multiHandler := slogmulti.Fanout(stdErrHandler, otelHandler)
log := slog.New(multiHandler)

fn := func(ctx context.Context) {
	// conventional logging sent to stderr as well as otel exporters
	log.InfoContext(ctx, "Starting function")
	log.ErrorContext(ctx, "Something bad has happened")
	log.DebugContext(ctx, "Debug me please", "foo", "bar")
}
fn(ctx)
Output:

Example (Spans)

ExampleConfig_simple demonstrates configuration setup for exporting telemetry spans in batches when they finish.

ctx := context.Background()

rsrc, err := resource.New(ctx,
	resource.WithTelemetrySDK(),
	resource.WithAttributes(
		semconv.ServiceName("example.service"),
		semconv.ServiceVersion(fmt.Sprintf("%d.%d.%d", 0, 0, 1)),
	),
)
if err != nil {
	panic(fmt.Sprintf("insufficient resource information: error = %v", err))
}

// add options here, else they will be discovered through env vars
exp, err := otlptracehttp.New(ctx)
if err != nil {
	panic(fmt.Sprintf("initializing trace exporter: error = %v", err))
}

cfg := Config{
	// LiveTraceExporters: []sdktrace.SpanExporter{exp}, // export when spans start and finish
	BatchedTraceExporters: []sdktrace.SpanExporter{exp}, // export when spans finish
	Resource:              rsrc,
}

ctx, err = cfg.Init(ctx)
if err != nil {
	panic(fmt.Sprintf("initializing OpenTelemetry: error = %v", err))
}
defer cfg.Shutdown(ctx) // ensure to shutdown, flushing remaining data to exporters

// start a tracer
t := otel.GetTracerProvider().Tracer("ExampleTracer")

fn := func(ctx context.Context) {
	//	start spans at the beginning of a function...
	ctx, span := t.Start(ctx, "ExampleSpan", trace.WithAttributes(attribute.String("Key", "Value")))
	defer span.End()

	// doing calulations...

	// something happened
	span.AddEvent("ExampleEvent")

	// ...
}

fn(ctx)
Output:

func (*Config) Init

func (c *Config) Init(ctx context.Context) (context.Context, error)

Init sets up the global OpenTelemetry providers for tracing, logging, and metrics. It does not setup handling of telemetry errors, use otel.SetErrorHandler to do so.

func (*Config) Shutdown

func (c *Config) Shutdown(ctx context.Context)

Shutdown shuts down the global OpenTelemetry providers, flushing any remaining data to the configured exporters.

NOTE: this function logs errors with the logger produced by logger.FromContext. This should probably be changed to return wrapped errors so they can be logged by the caller.

func (*Config) WrapSlogHandler

func (cfg *Config) WrapSlogHandler(name string, base slog.Handler) slog.Handler

WrapSlogHandler produces a slog.Handler that writes logs to OpenTelemetry and the base slog.Handler. Base handler is optional.

type EnvCarrier

type EnvCarrier struct {
	System bool
	Env    []string
}

EnvCarrier is used to inherit trace context from the environment.

func NewEnvCarrier

func NewEnvCarrier(system bool) *EnvCarrier

NewEnvCarrier initializes an EnvCarrier, optionally fetching from the system.

func (*EnvCarrier) Get

func (c *EnvCarrier) Get(key string) string

Get returns the value for a key.

func (*EnvCarrier) Keys

func (c *EnvCarrier) Keys() []string

Keys returns all keys in the environment.

func (*EnvCarrier) Set

func (c *EnvCarrier) Set(key, val string)

Set adds a key value pair to the environment.

type FilterLiveSpansExporter

type FilterLiveSpansExporter struct {
	sdktrace.SpanExporter
}

FilterLiveSpansExporter is a SpanExporter that filters out spans that are currently running, as indicated by an end time older than its start time (typically year 1753).

func (FilterLiveSpansExporter) ExportSpans

func (exp FilterLiveSpansExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error

ExportSpans passes each span to the span processor's OnEnd hook so that it can be batched and emitted more efficiently.

type LiveSpanProcessor

type LiveSpanProcessor struct {
	sdktrace.SpanProcessor
}

LiveSpanProcessor is a SpanProcessor whose OnStart calls OnEnd on the underlying SpanProcessor in order to send live telemetry.

func NewLiveSpanProcessor

func NewLiveSpanProcessor(exp sdktrace.SpanExporter) *LiveSpanProcessor

NewLiveSpanProcessor creates a span processor that exports spans on start and finish. Due to the frequency of exports, it is not recommended to be used with an exporter that sends spans to a remote collector.

func (*LiveSpanProcessor) OnStart

func (p *LiveSpanProcessor) OnStart(ctx context.Context, span sdktrace.ReadWriteSpan)

OnStart calls the underlying batch span processor's OnEnd func, which simply enqueues spans to be exported.

Directories

Path Synopsis
Package otelhelp defines CLI help commands with OTel configuration docs.
Package otelhelp defines CLI help commands with OTel configuration docs.

Jump to

Keyboard shortcuts

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