otel

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package otel provides framework-owned OpenTelemetry bootstrap and transport instrumentation helpers.

The package builds on the lower-level HTTP and gRPC OpenTelemetry wrappers in `github.com/CaliLuke/loom/http/middleware/otel` and `github.com/CaliLuke/loom/grpc/middleware/otel`. Use this package when a service wants Loom-owned provider bootstrap, HTTP metric-mode selection, and transport-level attribute hooks in addition to normal transport instrumentation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHTTPAttributes

func AddHTTPAttributes(ctx context.Context, attrs ...attribute.KeyValue)

AddHTTPAttributes appends request-scoped transport attributes to the active HTTP observability collector when the request is running inside HTTPMiddleware.

func GRPCClientOption

func GRPCClientOption(cfg GRPCConfig) grpc.DialOption

GRPCClientOption returns a gRPC dial option that installs OpenTelemetry stats handling using the official otelgrpc implementation.

func GRPCServerOption

func GRPCServerOption(cfg GRPCConfig) grpc.ServerOption

GRPCServerOption returns a gRPC server option that installs OpenTelemetry stats handling using the official otelgrpc implementation.

func HTTPMiddleware

func HTTPMiddleware(cfg HTTPConfig) func(http.Handler) http.Handler

HTTPMiddleware instruments an HTTP handler chain using the official OpenTelemetry HTTP middleware plus Loom-specific post-response enrichment hooks.

func WrapHTTPClient

func WrapHTTPClient(client *http.Client, cfg HTTPClientConfig) *http.Client

WrapHTTPClient returns a shallow copy of client with OpenTelemetry transport instrumentation configured according to cfg.

Types

type Config

type Config struct {
	// ServiceName is the logical service identity exported on resources.
	ServiceName string
	// ServiceVersion is the service version exported on resources.
	ServiceVersion string
	// Environment is the deployment environment exported on resources.
	Environment string
	// ResourceAttributes are merged into the provider resource.
	ResourceAttributes []attribute.KeyValue
	// Propagators configures request propagation for traces and logs.
	// New publishes it as the global propagator. When nil, New uses W3C
	// TraceContext and Baggage.
	Propagators propagation.TextMapPropagator
	// Traces configures trace provider bootstrap.
	Traces TraceConfig
	// Metrics configures metric provider bootstrap.
	Metrics MetricConfig
	// Logs configures log provider bootstrap.
	Logs LogConfig
}

Config configures framework-owned OpenTelemetry bootstrap.

type GRPCConfig

type GRPCConfig struct {
	// TracerProvider overrides the trace provider used by otelgrpc.
	TracerProvider trace.TracerProvider
	// MeterProvider overrides the meter provider used by otelgrpc.
	MeterProvider metric.MeterProvider
	// Propagators overrides the propagators used by otelgrpc. When nil,
	// otelgrpc uses the global OpenTelemetry propagator obtained when the
	// option is created, so publish it first, for example with New.
	Propagators propagation.TextMapPropagator
}

GRPCConfig configures gRPC OpenTelemetry instrumentation.

type HTTPAttributeSource

type HTTPAttributeSource interface {
	Attributes(*http.Request, HTTPRequestInfo) []attribute.KeyValue
}

HTTPAttributeSource returns span attributes for a completed request.

type HTTPClientConfig

type HTTPClientConfig struct {
	// ServiceName names the downstream dependency in client span names,
	// which become "{method} {ServiceName}", such as "GET github", so
	// backends that group by span name keep methods apart. When empty,
	// spans keep the otelhttp default name "HTTP {method}".
	ServiceName string
	// MetricMode selects otelhttp metrics or suppression for the client
	// transport.
	MetricMode HTTPMetricMode
	// TracerProvider overrides the trace provider used by otelhttp.
	TracerProvider trace.TracerProvider
	// MeterProvider overrides the meter provider used by otelhttp.
	MeterProvider metric.MeterProvider
	// Propagators overrides the propagators used by otelhttp. When nil,
	// otelhttp uses the global OpenTelemetry propagator obtained when
	// WrapHTTPClient is called, so publish it first, for example with New.
	Propagators propagation.TextMapPropagator
}

HTTPClientConfig configures HTTP client-side OpenTelemetry instrumentation.

type HTTPConfig

type HTTPConfig struct {
	// ServiceName is the fallback operation name when no Loom route pattern is
	// available.
	ServiceName string
	// MetricMode selects otelhttp metrics, custom metrics, both, or neither.
	MetricMode HTTPMetricMode
	// TracerProvider overrides the trace provider used by otelhttp.
	TracerProvider trace.TracerProvider
	// MeterProvider overrides the meter provider used by otelhttp.
	MeterProvider metric.MeterProvider
	// Propagators overrides the propagators used by otelhttp. When nil,
	// otelhttp uses the global OpenTelemetry propagator obtained when
	// HTTPMiddleware is called, so publish it first, for example with New.
	Propagators propagation.TextMapPropagator
	// AttributeSource returns post-response span attributes.
	AttributeSource HTTPAttributeSource
	// MetricsRecorder records custom post-response HTTP metrics.
	MetricsRecorder HTTPMetricsRecorder
}

HTTPConfig configures HTTP server-side OpenTelemetry instrumentation.

type HTTPMetricMode

type HTTPMetricMode string

HTTPMetricMode controls whether transport-level HTTP metrics are emitted by otelhttp, by a custom recorder, by both, or by neither.

const (
	// HTTPMetricModeOTelOnly emits otelhttp metrics only.
	HTTPMetricModeOTelOnly HTTPMetricMode = "otel_only"
	// HTTPMetricModeCustomOnly suppresses otelhttp metrics and uses only the
	// custom recorder.
	HTTPMetricModeCustomOnly HTTPMetricMode = "custom_only"
	// HTTPMetricModeBoth emits both otelhttp metrics and the custom recorder.
	HTTPMetricModeBoth HTTPMetricMode = "both"
	// HTTPMetricModeNone emits neither otelhttp metrics nor custom metrics.
	HTTPMetricModeNone HTTPMetricMode = "none"
)

type HTTPMetricsRecorder

type HTTPMetricsRecorder interface {
	Record(context.Context, *http.Request, HTTPRequestInfo)
}

HTTPMetricsRecorder records custom transport metrics for a completed request.

type HTTPRequestInfo

type HTTPRequestInfo struct {
	// Method is the HTTP method.
	Method string
	// Route is the Loom route pattern or fallback method-path name.
	Route string
	// StatusCode is the final HTTP response status.
	StatusCode int
	// Duration is the total request duration observed by the middleware.
	Duration time.Duration
	// PathValues contains resolved path parameter values keyed by parameter
	// name when the route pattern contains named segments.
	PathValues map[string]string
	// Authenticated is reserved for consumers that want to project auth state
	// into the request info externally; the framework does not infer it.
	Authenticated bool
}

HTTPRequestInfo describes a completed HTTP request as seen by the observability middleware.

type LogConfig

type LogConfig struct {
	// Enabled enables log provider bootstrap.
	Enabled bool
	// Protocol selects the OTLP transport. Empty selects http/protobuf.
	Protocol OTLPProtocol
	// Endpoint is the OTLP collector host:port, without a scheme or path. It
	// enables the OTLP exporter.
	// HTTP exports go to the default /v1/logs path unless
	// OTEL_EXPORTER_OTLP_* environment variables set a path. Set at most one
	// of Endpoint and EndpointURL.
	Endpoint string
	// EndpointURL is the complete OTLP endpoint URL, with the same rules as
	// TraceConfig.EndpointURL.
	EndpointURL string
	// Insecure disables TLS for an Endpoint export. When false, an
	// OTEL_EXPORTER_OTLP_* environment variable may still select TLS.
	Insecure bool
	// Headers are sent on OTLP export requests.
	Headers map[string]string
	// BatchOptions tune the batch processor of the OTLP exporter. They
	// require Endpoint or EndpointURL.
	BatchOptions []sdklog.BatchProcessorOption
	// Processors are registered after the OTLP exporter, or alone when no
	// endpoint is set. They are registered only when the
	// section is enabled. A successful New with the section enabled
	// transfers ownership: Runtime.Shutdown shuts them down. A failed New,
	// or a disabled section, leaves them owned by the caller. Each entry
	// must be non-nil and appear once.
	Processors []sdklog.Processor
}

LogConfig configures log provider bootstrap.

type MetricConfig

type MetricConfig struct {
	// Enabled enables metric provider bootstrap.
	Enabled bool
	// Protocol selects the OTLP transport. Empty selects http/protobuf.
	Protocol OTLPProtocol
	// Endpoint is the OTLP collector host:port, without a scheme or path. It
	// enables the OTLP exporter.
	// HTTP exports go to the default /v1/metrics path unless
	// OTEL_EXPORTER_OTLP_* environment variables set a path. Set at most one
	// of Endpoint and EndpointURL.
	Endpoint string
	// EndpointURL is the complete OTLP endpoint URL, with the same rules as
	// TraceConfig.EndpointURL.
	EndpointURL string
	// Insecure disables TLS for an Endpoint export. When false, an
	// OTEL_EXPORTER_OTLP_* environment variable may still select TLS.
	Insecure bool
	// Headers are sent on OTLP export requests.
	Headers map[string]string
	// ReaderOptions tune the periodic reader of the OTLP exporter, such as
	// sdkmetric.WithInterval. They require Endpoint or EndpointURL.
	ReaderOptions []sdkmetric.PeriodicReaderOption
	// Readers are registered after the OTLP reader, or alone when no
	// endpoint is set. They are registered only when the
	// section is enabled. A successful New with the section enabled
	// transfers ownership: Runtime.Shutdown shuts them down. A failed New,
	// or a disabled section, leaves them owned by the caller. Each entry
	// must be non-nil and appear once.
	Readers []sdkmetric.Reader
}

MetricConfig configures metric provider bootstrap.

type OTLPProtocol added in v1.12.0

type OTLPProtocol string

OTLPProtocol selects the OTLP exporter transport, using the values of OTEL_EXPORTER_OTLP_PROTOCOL.

const (
	// OTLPProtocolHTTPProtobuf exports protobuf over HTTP, the default.
	OTLPProtocolHTTPProtobuf OTLPProtocol = "http/protobuf"
	// OTLPProtocolGRPC exports over gRPC.
	OTLPProtocolGRPC OTLPProtocol = "grpc"
)

type Runtime

type Runtime struct {
	// TracerProvider is the initialized trace provider, if enabled.
	TracerProvider trace.TracerProvider
	// MeterProvider is the initialized metric provider, if enabled.
	MeterProvider metric.MeterProvider
	// LoggerProvider is the initialized log provider, if enabled.
	LoggerProvider log.LoggerProvider
	// Propagators is the propagator set used by this runtime.
	Propagators propagation.TextMapPropagator
	// Shutdown closes initialized providers in reverse initialization order.
	Shutdown func(context.Context) error
}

Runtime contains the initialized OpenTelemetry providers.

func New

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

New initializes the configured OpenTelemetry providers and returns the runtime. It publishes enabled providers globally only after all construction succeeds. Every successful call also publishes the runtime propagator globally, whether or not any provider is enabled, so instrumentation with nil Propagators extracts and injects request context. To keep a propagator the application registered earlier, pass it as Config.Propagators. On failure it attempts reverse-order cleanup with an uncanceled five-second context and returns the construction error joined with any cleanup errors. Failed construction leaves the existing global providers and propagator intact.

type TraceConfig

type TraceConfig struct {
	// Enabled enables trace provider bootstrap.
	Enabled bool
	// Protocol selects the OTLP transport. Empty selects http/protobuf.
	Protocol OTLPProtocol
	// Endpoint is the OTLP collector host:port, without a scheme or path. It
	// enables the OTLP exporter.
	// HTTP exports go to the default /v1/traces path unless
	// OTEL_EXPORTER_OTLP_* environment variables set a path. Set at most one
	// of Endpoint and EndpointURL.
	Endpoint string
	// EndpointURL is the complete OTLP endpoint URL with an http or https
	// scheme. It enables the OTLP exporter. For http/protobuf it is the full
	// signal URL, path included, as in OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; a
	// URL without a path posts to the root path. For grpc it must not have a
	// path. The scheme selects TLS, so Insecure must not be set with it.
	EndpointURL string
	// Insecure disables TLS for an Endpoint export. When false, an
	// OTEL_EXPORTER_OTLP_* environment variable may still select TLS.
	Insecure bool
	// Headers are sent on OTLP export requests.
	Headers map[string]string
	// SampleRatio controls TraceID-based sampling of root spans.
	// Valid local and remote parents retain their sampling decision.
	// Values <= 0 or > 1 use the default ratio of 1.
	SampleRatio float64
	// BatchOptions tune the batch span processor of the OTLP exporter. They
	// require Endpoint or EndpointURL.
	BatchOptions []sdktrace.BatchSpanProcessorOption
	// SpanProcessors are registered after the OTLP exporter, or alone when
	// no endpoint is set. They are registered only when the
	// section is enabled. A successful New with the section enabled
	// transfers ownership: Runtime.Shutdown shuts them down. A failed New,
	// or a disabled section, leaves them owned by the caller. Each entry
	// must be non-nil and appear once.
	SpanProcessors []sdktrace.SpanProcessor
}

TraceConfig configures trace provider bootstrap.

Directories

Path Synopsis
internal
Package slogbridge provides a standard-library log/slog.Handler that emits log records directly to the OpenTelemetry Logs API (`go.opentelemetry.io/otel/log`).
Package slogbridge provides a standard-library log/slog.Handler that emits log records directly to the OpenTelemetry Logs API (`go.opentelemetry.io/otel/log`).

Jump to

Keyboard shortcuts

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