Documentation
¶
Overview ¶
Package otx (OpenTelemetry eXtensions) provides a config-driven OpenTelemetry tracing layer for Go services.
Overview ¶
The otx package wraps official OTel APIs, providing:
- Config-driven sampling (OTel standard: always_on, always_off, traceidratio, parentbased_*)
- Pluggable span naming via SpanNamer interface
- W3C TraceContext and Baggage propagation (OTEL_PROPAGATORS)
- Context-aware span helpers for tracing operations
Quick Start ¶
Initialize the tracer provider and global tracer. Use BoolPtr to set the *bool Enabled fields when building a config programmatically:
cfg := &otx.TelemetryConfig{
Enabled: otx.BoolPtr(true),
ServiceName: "my-service",
}
tp, err := otx.NewTracerProvider(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer tp.Shutdown(ctx)
otx.InitTracing(tp.Tracer("my-service"), otx.DefaultNamer{})
Use span helpers in your code:
func ProcessBatch(ctx context.Context, batch []Item) error {
ctx, span := otx.Start(ctx, "ProcessBatch")
defer span.End()
otx.SetAttributes(ctx, attribute.Int("batch.size", len(batch)))
if err := process(ctx, batch); err != nil {
otx.RecordError(ctx, err)
return err
}
otx.SetSuccess(ctx)
return nil
}
Configuration ¶
Configure via YAML or environment variables (OTel standard):
otx:
enabled: true
serviceName: "my-service" # OTEL_SERVICE_NAME
otlp:
endpoint: "otel-collector:4318" # OTEL_EXPORTER_OTLP_ENDPOINT
traces:
sampling:
sampler: "parentbased_traceidratio" # OTEL_TRACES_SAMPLER
samplerArg: 0.1 # OTEL_TRACES_SAMPLER_ARG
propagation:
propagators: "tracecontext,baggage" # OTEL_PROPAGATORS
Span Naming ¶
The SpanNamer interface controls how operation names become span names. DefaultNamer passes the operation name through unchanged. For structured, signal-specific names use helpers such as NameHTTP, NameRPC, NameMessaging, and NameDB.
Baggage ¶
Use baggage helpers to propagate metadata across services:
ctx = otx.MustSetBaggage(ctx, "tenant.id", tenantID) // ... later in downstream service tenantID := otx.GetBaggage(ctx, "tenant.id")
Middleware ¶
The otx/middleware sub-package provides gRPC and HTTP instrumentation. See that package for details.
Index ¶
- Variables
- func AddEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)
- func AllBaggage(ctx context.Context) map[string]string
- func BoolPtr(v bool) *bool
- func BuildPropagator(cfg *PropConfig) propagation.TextMapPropagator
- func BuildResource(ctx context.Context, cfg *TelemetryConfig) (*resource.Resource, error)
- func DeleteBaggage(ctx context.Context, key string) context.Context
- func ExtractGRPC(ctx context.Context, md metadata.MD) context.Context
- func ExtractHTTP(ctx context.Context, headers http.Header) context.Context
- func GetBaggage(ctx context.Context, key string) string
- func InitTracing(tracer trace.Tracer, namer SpanNamer)
- func InjectGRPC(ctx context.Context, md metadata.MD)
- func InjectHTTP(ctx context.Context, headers http.Header)
- func LookupBaggage(ctx context.Context, key string) (string, bool)
- func MustSetBaggage(ctx context.Context, key, value string) context.Context
- func NameDB(verb, table string) string
- func NameHTTP(method, route string) string
- func NameMessaging(verb, destination string) string
- func NameRPC(service, method string) string
- func NewLoggerProvider(ctx context.Context, cfg *TelemetryConfig) (*sdklog.LoggerProvider, error)
- func NewMeterProvider(ctx context.Context, cfg *TelemetryConfig) (*sdkmetric.MeterProvider, error)
- func NewTracerProvider(ctx context.Context, cfg *TelemetryConfig) (*sdktrace.TracerProvider, error)
- func RecordError(ctx context.Context, err error, opts ...trace.EventOption)
- func SetAttributes(ctx context.Context, attrs ...attribute.KeyValue)
- func SetBaggage(ctx context.Context, key, value string) (context.Context, error)
- func SetSuccess(ctx context.Context)
- func Span(ctx context.Context) trace.Spandeprecated
- func SpanFromContext(ctx context.Context) trace.Span
- func SpanID(ctx context.Context) string
- func Start(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartClient(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartConsumer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartInternal(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartProducer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func StartServer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func TraceID(ctx context.Context) string
- type DefaultNamer
- type ExporterConfig
- type LogsConfig
- type MetricsConfig
- type OTLPConfig
- type PropConfig
- type SamplingConfig
- type SpanNamer
- type TelemetryConfig
- func (c *TelemetryConfig) GetOTLPConfig() *OTLPConfig
- func (c *TelemetryConfig) GetOTLPEndpoint() stringdeprecated
- func (c *TelemetryConfig) GetSamplingConfig() *SamplingConfig
- func (c *TelemetryConfig) GetTracesExporter() string
- func (c *TelemetryConfig) IsEnabled() bool
- func (c *TelemetryConfig) ValidateEndpoints() error
- type TracesConfig
Constants ¶
This section is empty.
Variables ¶
var ErrDisabled = errors.New("otx: telemetry is disabled")
ErrDisabled is returned when telemetry is disabled.
var ErrLogsDisabled = errors.New("otx: logs export is disabled")
ErrLogsDisabled is returned when log export is disabled.
var ErrMetricsDisabled = errors.New("otx: metrics export is disabled")
ErrMetricsDisabled is returned when metrics export is disabled.
var ErrServiceNameRequired = errors.New("otx: service name is required")
ErrServiceNameRequired is returned when ServiceName is empty but telemetry is enabled.
var ErrTracesDisabled = fmt.Errorf("otx: traces export is disabled: %w", ErrDisabled)
ErrTracesDisabled is returned by NewTracerProvider when telemetry is enabled but the traces signal is explicitly disabled. It wraps ErrDisabled, so callers that match either errors.Is(err, ErrTracesDisabled) or errors.Is(err, ErrDisabled) succeed.
var ErrUnknownExporter = errors.New("otx: unknown exporter type")
ErrUnknownExporter is returned by the exporter builders when the configured exporter type is not one of the recognized values (otlp, console/stdout, none/nop). It is wrapped with the offending type for diagnostics; match it with errors.Is(err, ErrUnknownExporter).
Functions ¶
func AllBaggage ¶
AllBaggage returns all baggage members as a map.
func BoolPtr ¶ added in v1.1.0
BoolPtr returns a pointer to v. It is the exported helper for setting the *bool Enabled fields on TelemetryConfig and the per-signal configs when building a config programmatically, e.g. TelemetryConfig{Enabled: otx.BoolPtr(true)}.
func BuildPropagator ¶ added in v1.1.0
func BuildPropagator(cfg *PropConfig) propagation.TextMapPropagator
BuildPropagator returns the OTel text map propagator derived from cfg — the same propagator NewTracerProvider installs as the global propagator. It is exported and side-effect-free (it does not mutate any OTel global) so callers that export metrics or logs but not traces can install propagation independently via otel.SetTextMapPropagator(otx.BuildPropagator(cfg)).
A nil cfg yields the W3C default (tracecontext + baggage). Unknown propagator names and the known-but-unimplemented b3/b3multi/jaeger/xray/ottrace names emit a diagnostic via otel.Handle and are otherwise ignored.
func BuildResource ¶ added in v1.1.0
BuildResource returns the OTel resource derived from cfg — the same resource NewTracerProvider, NewLoggerProvider, and NewMeterProvider attach to their providers. It is exported for advanced wiring that needs the resource identity outside the standard providers (custom SDK components, the otx/zaplog adapter), so logs and traces carry identical resource attributes and join in the backend.
func DeleteBaggage ¶
DeleteBaggage removes a key from baggage in the context.
func ExtractGRPC ¶
ExtractGRPC extracts propagation fields from gRPC metadata using the global text map propagator. Exactly what is extracted depends on the propagators configured via OTEL_PROPAGATORS or BuildPropagator.
func ExtractHTTP ¶
ExtractHTTP extracts propagation fields from HTTP headers using the global text map propagator. Exactly what is extracted depends on the propagators configured via OTEL_PROPAGATORS or BuildPropagator.
func GetBaggage ¶
GetBaggage retrieves a value from baggage in the context.
It returns an empty string when the key is absent, which is indistinguishable from a key present with an empty value. Use LookupBaggage when that distinction matters.
func InitTracing ¶
InitTracing sets up the global tracer and namer. It is typically called once during application initialization, but is safe to call multiple times: each call atomically replaces the previous tracer and namer (latest wins).
A nil namer is allowed and selects the default namer, which returns operation names unchanged (see DefaultNamer).
func InjectGRPC ¶
InjectGRPC injects propagation fields into gRPC metadata using the global text map propagator. Exactly what is carried depends on the propagators configured via OTEL_PROPAGATORS or BuildPropagator.
func InjectHTTP ¶
InjectHTTP injects propagation fields into HTTP headers using the global text map propagator. Exactly what is carried (trace context, baggage, or both) depends on the propagators configured via OTEL_PROPAGATORS or BuildPropagator.
func LookupBaggage ¶ added in v1.1.0
LookupBaggage retrieves a value from baggage in the context and reports whether the key is present.
The returned bool is false when the key is absent and true when the key is present, even if its value is the empty string. This lets callers tell an absent key apart from a key carrying an empty value, which GetBaggage cannot.
func MustSetBaggage ¶
MustSetBaggage adds a key-value pair to baggage, panicking on error. Use when key/value are known to be valid (e.g., hardcoded keys).
See SetBaggage for key/value format requirements. Panics if key or value violates W3C Baggage specification.
func NameDB ¶
NameDB returns a compliant span name for a database operation: "verb table". Example: "SELECT users"
func NameHTTP ¶
NameHTTP returns a compliant span name for an HTTP request: "METHOD /route". Example: "GET /users/{id}"
func NameMessaging ¶
NameMessaging returns a compliant span name for a messaging operation: "verb destination". Example: "publish orders"
func NameRPC ¶
NameRPC returns a compliant span name for an RPC call: "Service/Method". Example: "Greeter/SayHello"
func NewLoggerProvider ¶
func NewLoggerProvider(ctx context.Context, cfg *TelemetryConfig) (*sdklog.LoggerProvider, error)
NewLoggerProvider initializes the OpenTelemetry LoggerProvider. Returns ErrDisabled if telemetry is not enabled, or ErrLogsDisabled if telemetry is enabled but the logs signal is off. These errors are distinct errors.Is targets: ErrLogsDisabled does not wrap ErrDisabled. Use this with shared/logging's WithLoggerProvider integration.
Side effects: on success this mutates the OTel log global — it calls global.SetLoggerProvider, replacing any previously installed global logger provider. It does not install the global propagator (only NewTracerProvider does); see BuildPropagator if you need propagation without traces.
func NewMeterProvider ¶
func NewMeterProvider(ctx context.Context, cfg *TelemetryConfig) (*sdkmetric.MeterProvider, error)
NewMeterProvider initializes the OpenTelemetry MeterProvider. Returns ErrDisabled if telemetry is not enabled, or ErrMetricsDisabled if telemetry is enabled but the metrics signal is off. These errors are distinct errors.Is targets: ErrMetricsDisabled does not wrap ErrDisabled.
Side effects: on success this mutates the OTel global — it calls otel.SetMeterProvider, replacing any previously installed global meter provider. It does not install the global propagator (only NewTracerProvider does); see BuildPropagator if you need propagation without traces.
func NewTracerProvider ¶
func NewTracerProvider(ctx context.Context, cfg *TelemetryConfig) (*sdktrace.TracerProvider, error)
NewTracerProvider initializes the OpenTelemetry TracerProvider. Returns ErrDisabled if telemetry is not enabled in config, or ErrTracesDisabled (which wraps ErrDisabled) if telemetry is enabled but the traces signal is off.
Side effects: on success this mutates OTel globals — it calls otel.SetTracerProvider and otel.SetTextMapPropagator, replacing any previously installed global tracer provider and propagator. The global propagator is installed only by this constructor; services that export metrics or logs but not traces should call otel.SetTextMapPropagator(otx.BuildPropagator(cfg.Propagation)) to retain context propagation.
func RecordError ¶
func RecordError(ctx context.Context, err error, opts ...trace.EventOption)
RecordError records an error on the current span and sets status. If err is nil, this is a no-op.
func SetAttributes ¶
SetAttributes sets attributes on the current span.
func SetBaggage ¶
SetBaggage adds a key-value pair to baggage in the context.
Keys and values must conform to the W3C Baggage specification:
- Keys: Must be valid HTTP header tokens (alphanumeric, hyphen, underscore, tilde). Invalid characters: spaces, control chars, and most punctuation.
- Values: Must be URL-encoded or percent-encoded if containing special characters. Invalid characters: control chars (0x00-0x1F, 0x7F).
Returns an error if key or value violates these constraints.
func SetSuccess ¶
SetSuccess marks the current span as successful.
func SpanFromContext ¶
SpanFromContext retrieves the current span from the context.
func Start ¶
func Start(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
Start begins a new span with the configured namer applied.
func StartClient ¶
func StartClient(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartClient begins a new client span (e.g., making an outgoing request).
func StartConsumer ¶
func StartConsumer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartConsumer begins a new consumer span (e.g., processing a message from a queue).
func StartInternal ¶
func StartInternal(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartInternal begins a new internal span (e.g., local processing).
func StartProducer ¶
func StartProducer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartProducer begins a new producer span (e.g., publishing a message to Kafka/NATS).
Types ¶
type DefaultNamer ¶
type DefaultNamer struct{}
DefaultNamer returns operation names unchanged. This is a pass-through implementation; it does not apply any semantic-convention structuring. For structured, signal-specific span names use NameHTTP, NameRPC, NameMessaging, or NameDB instead.
func (DefaultNamer) Name ¶
func (DefaultNamer) Name(operation string) string
Name returns the operation name as is.
type ExporterConfig ¶
type ExporterConfig struct {
// Type determines the exporter implementation.
// Maps to OTEL_TRACES_EXPORTER.
// Options: "otlp", "console", "stdout", "none".
Type string `yaml:"type" json:"type" env:"OTEL_TRACES_EXPORTER" default:"otlp" validate:"oneof=otlp console stdout none"`
// Endpoint is the OTLP collector endpoint.
Endpoint string `yaml:"endpoint" json:"endpoint" env:"OTEL_EXPORTER_OTLP_ENDPOINT" default:"localhost:4317"`
// Insecure disables TLS for the OTLP connection.
Insecure *bool `yaml:"insecure" json:"insecure" env:"OTEL_EXPORTER_OTLP_INSECURE" default:"true"`
// Headers adds custom headers to OTLP requests.
// Maps to OTEL_EXPORTER_OTLP_HEADERS; parsed by otx (see LoadConfig/ParseConfig).
// Avoid logging this value, as it may contain sensitive credentials.
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
// Protocol determines the OTLP transport protocol.
Protocol string `` /* 131-byte string literal not displayed */
// Timeout is the timeout for exporter operations.
Timeout time.Duration `yaml:"timeout" json:"timeout" env:"OTEL_EXPORTER_OTLP_TIMEOUT" default:"10s" validate:"gte=0"`
// Compression sets the compression algorithm for OTLP.
Compression string `` /* 131-byte string literal not displayed */
}
ExporterConfig configures the trace exporter. Deprecated: Use OTLPConfig for shared settings and TracesConfig.Exporter for type. Kept for backward compatibility.
func (*ExporterConfig) IsInsecure ¶
func (c *ExporterConfig) IsInsecure() bool
IsInsecure returns true if insecure connection is enabled. Defaults to true if nil.
type LogsConfig ¶
type LogsConfig struct {
// Enabled controls whether OTel log export is active.
// Defaults to false (opt-in for logs).
Enabled *bool `yaml:"enabled" json:"enabled" default:"false"`
// Exporter determines the log exporter type.
// Maps to OTEL_LOGS_EXPORTER.
// Options: "otlp", "console", "stdout", "none".
Exporter string `yaml:"exporter" json:"exporter" env:"OTEL_LOGS_EXPORTER" default:"otlp" validate:"oneof=otlp console stdout none"`
// Endpoint overrides OTLP.Endpoint for logs.
// Maps to OTEL_EXPORTER_OTLP_LOGS_ENDPOINT.
// In most cases, leave this empty and set OTLP.Endpoint instead.
// Only use this when logs need a different endpoint than other signals.
Endpoint string `yaml:"endpoint,omitempty" json:"endpoint,omitempty" env:"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"`
// Protocol overrides OTLP.Protocol for logs.
// Maps to OTEL_EXPORTER_OTLP_LOGS_PROTOCOL.
// Options: "grpc", "http/protobuf", "http".
// The otx/zaplog adapter routes "grpc" to zapwire's hand-rolled OTLP/gRPC
// client and anything else to OTLP/HTTP. Default is "http/protobuf" (port 4318).
Protocol string `` /* 141-byte string literal not displayed */
// MinLevel is the minimum zap level the otx/zaplog OTLP core emits.
// It gates log-export cost (e.g. "warn" ships only warn and above).
// Defaults to "info" when empty. Ignored by the SDK log pipeline.
MinLevel string `yaml:"minLevel,omitempty" json:"minLevel,omitempty" validate:"omitempty,oneof=debug info warn error dpanic panic fatal"`
// DrainTimeout bounds the total time w.Sync()/w.Close() spend draining the
// zapwire queue at shutdown before dropping the remainder (dropped count
// accumulates in the writer's DroppedLogs counter). This caps the worst-case
// shutdown latency a stalled or slow receiver can impose.
//
// The bound is soft: an export attempt already in flight still runs to its
// Timeout deadline, so the effective ceiling is DrainTimeout + at most one
// in-flight request. A healthy receiver completes the drain long before the
// bound; the option only trims a hostile or broken receiver's tail.
//
// Zero (default) keeps the legacy unbounded behaviour: Sync waits until
// every queued record is exported or dropped by retry exhaustion. Applies
// only to the otx/zaplog zapwire data plane; ignored by the SDK log pipeline.
DrainTimeout time.Duration `yaml:"drainTimeout,omitempty" json:"drainTimeout,omitempty" validate:"gte=0"`
}
LogsConfig configures the logging subsystem (OTel log bridge). This integrates with shared/logging via WithLoggerProvider.
func (*LogsConfig) IsEnabled ¶
func (c *LogsConfig) IsEnabled() bool
IsEnabled returns true if OTel log export is enabled. Logs default OFF: a nil receiver or nil Enabled field reports false, so log export is opt-in and stays off unless Enabled is explicitly set to true. This is the opposite of TracesConfig, which defaults on.
type MetricsConfig ¶
type MetricsConfig struct {
// Enabled controls whether metrics collection is active.
// Defaults to false (opt-in for metrics).
Enabled *bool `yaml:"enabled" json:"enabled" default:"false"`
// Exporter determines the metrics exporter type.
// Maps to OTEL_METRICS_EXPORTER.
// Options: "otlp", "console", "stdout", "none".
Exporter string `yaml:"exporter" json:"exporter" env:"OTEL_METRICS_EXPORTER" default:"otlp" validate:"oneof=otlp console stdout none"`
// Endpoint overrides OTLP.Endpoint for metrics.
// Maps to OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.
// In most cases, leave this empty and set OTLP.Endpoint instead.
// Only use this when metrics need a different endpoint than other signals.
Endpoint string `yaml:"endpoint,omitempty" json:"endpoint,omitempty" env:"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"`
// Interval is the export interval for periodic metric reader.
// Maps to OTEL_METRIC_EXPORT_INTERVAL (milliseconds if numeric).
// Defaults to 60s.
Interval time.Duration `yaml:"interval,omitempty" json:"interval,omitempty" env:"OTEL_METRIC_EXPORT_INTERVAL" default:"60s" validate:"omitempty,gt=0"`
}
MetricsConfig configures the metrics subsystem.
func (*MetricsConfig) IsEnabled ¶
func (c *MetricsConfig) IsEnabled() bool
IsEnabled returns true if metrics collection is enabled. Metrics default OFF: a nil receiver or nil Enabled field reports false, so metrics collection is opt-in and stays off unless Enabled is explicitly set to true. This is the opposite of TracesConfig, which defaults on.
type OTLPConfig ¶
type OTLPConfig struct {
// Endpoint is the OTLP collector endpoint.
// Maps to OTEL_EXPORTER_OTLP_ENDPOINT.
//
// Accepted forms (both protocols):
// - Bare "host:port" (e.g., "localhost:4317" for gRPC, "localhost:4318"
// for HTTP) — canonical form; TLS controlled by the Insecure flag.
// - Scheme-bearing URL (e.g., "https://collector:4317") — scheme takes
// precedence over Insecure; https:// is always TLS, http:// is always
// plain. Any other scheme is rejected at load time.
//
// The effective default is protocol-aware and applied at exporter/zaplog
// resolution, not at config load: http/protobuf → localhost:4318,
// grpc → localhost:4317. Leave empty to use the protocol default.
Endpoint string `yaml:"endpoint" json:"endpoint" env:"OTEL_EXPORTER_OTLP_ENDPOINT"`
// Insecure disables TLS for the OTLP connection.
// Maps to OTEL_EXPORTER_OTLP_INSECURE.
//
// WARNING: the otx default is true (plaintext), which differs from the OTel
// spec default (false). A bare host:port endpoint with Insecure unset is
// exported over plaintext — including any credential-bearing Headers. This
// is safe for the localhost default but a leak against a remote collector;
// otx emits a one-time diagnostic via otel.Handle in that case. Set this to
// false, or use an https:// Endpoint (the scheme forces TLS regardless of
// this flag), when exporting to a remote host.
Insecure *bool `yaml:"insecure" json:"insecure" env:"OTEL_EXPORTER_OTLP_INSECURE" default:"true"`
// Headers adds custom headers to OTLP requests.
// Maps to OTEL_EXPORTER_OTLP_HEADERS (comma-separated key=value pairs, per the
// OTel spec). The env value is parsed by otx (see LoadConfig/ParseConfig) and,
// when set, fully replaces any value loaded from the config file. A legacy
// key:value form is also accepted for backward compatibility.
// Avoid logging this value, as it may contain sensitive credentials.
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
// Protocol determines the OTLP transport protocol.
// Maps to OTEL_EXPORTER_OTLP_PROTOCOL.
// Options: "grpc", "http/protobuf", "http".
Protocol string `` /* 130-byte string literal not displayed */
// Timeout is the timeout for exporter operations.
// Maps to OTEL_EXPORTER_OTLP_TIMEOUT.
Timeout time.Duration `yaml:"timeout" json:"timeout" env:"OTEL_EXPORTER_OTLP_TIMEOUT" default:"10s" validate:"gte=0"`
// Compression sets the compression algorithm for OTLP.
// Maps to OTEL_EXPORTER_OTLP_COMPRESSION.
// Options: "gzip", "none".
Compression string `` /* 131-byte string literal not displayed */
}
OTLPConfig contains shared OTLP exporter settings. These settings apply to all signals unless overridden by signal-specific config.
func (*OTLPConfig) IsInsecure ¶
func (c *OTLPConfig) IsInsecure() bool
IsInsecure returns true if insecure (plaintext) connection is enabled. It defaults to true when the receiver or the Insecure field is nil — see the Insecure field doc for the plaintext-default caveat.
type PropConfig ¶
type PropConfig struct {
// Propagators specifies which propagators to use.
// Maps to OTEL_PROPAGATORS (comma-separated list).
// Known values: "tracecontext", "baggage", "b3", "b3multi", "jaeger", "xray", "none".
// Defaults to "tracecontext,baggage" (W3C standards).
Propagators string `yaml:"propagators" json:"propagators" env:"OTEL_PROPAGATORS" default:"tracecontext,baggage"`
}
PropConfig configures context propagation. Maps to OTEL_PROPAGATORS.
func (*PropConfig) HasBaggage ¶
func (c *PropConfig) HasBaggage() bool
HasBaggage returns true if baggage propagator is enabled.
func (*PropConfig) HasTraceContext ¶
func (c *PropConfig) HasTraceContext() bool
HasTraceContext returns true if tracecontext propagator is enabled.
type SamplingConfig ¶
type SamplingConfig struct {
// Sampler determines which sampler to use.
// Maps to OTEL_TRACES_SAMPLER.
// Options: "always_on", "always_off", "traceidratio",
// "parentbased_always_on", "parentbased_always_off", "parentbased_traceidratio".
// Defaults to "parentbased_always_on" (OTel default).
Sampler string `` /* 208-byte string literal not displayed */
// SamplerArg is the argument for ratio-based samplers.
// Maps to OTEL_TRACES_SAMPLER_ARG.
// For traceidratio and parentbased_traceidratio: sampling probability 0.0 to 1.0.
// Values outside [0.0, 1.0] have undefined behavior.
// Defaults to 1.0 (100%).
SamplerArg float64 `yaml:"samplerArg" json:"samplerArg" env:"OTEL_TRACES_SAMPLER_ARG" default:"1.0" validate:"gte=0,lte=1"`
}
SamplingConfig configures the trace sampling strategy. Maps to OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG.
type TelemetryConfig ¶
type TelemetryConfig struct {
// Enabled controls whether the OTX telemetry system is active.
Enabled *bool `yaml:"enabled" json:"enabled" default:"false" env:"OTX_ENABLED"`
// ServiceName is the name of the service for telemetry identification.
// Maps to OTEL_SERVICE_NAME.
ServiceName string `yaml:"serviceName" json:"serviceName" env:"OTEL_SERVICE_NAME" validate:"required_if=Enabled true"`
// Version is the service version (e.g., git commit or semantic version).
// Used in service.version resource attribute.
Version string `yaml:"version" json:"version" env:"OTEL_SERVICE_VERSION"`
// Environment is the deployment environment (e.g., production, development).
// Used in deployment.environment resource attribute.
Environment string `yaml:"environment" json:"environment" env:"OTEL_DEPLOYMENT_ENVIRONMENT" default:"development"`
// ResourceAttributes contains additional resource attributes as key=value pairs.
// Maps to OTEL_RESOURCE_ATTRIBUTES (comma-separated key=value pairs, per the
// OTel spec). The env value is parsed by otx (see LoadConfig/ParseConfig) and,
// when set, fully replaces any value loaded from the config file. A legacy
// key:value form is also accepted for backward compatibility.
ResourceAttributes map[string]string `yaml:"resourceAttributes,omitempty" json:"resourceAttributes,omitempty"`
// OTLP contains shared OTLP exporter settings used by all signals (traces, logs, metrics).
// Signal-specific settings can override these.
OTLP *OTLPConfig `yaml:"otlp,omitempty" json:"otlp,omitempty"`
// Traces configures the tracing subsystem.
Traces *TracesConfig `yaml:"traces,omitempty" json:"traces,omitempty"`
// Logs configures the logging subsystem (OTel log bridge).
// Used by shared/logging's WithLoggerProvider integration.
Logs *LogsConfig `yaml:"logs,omitempty" json:"logs,omitempty"`
// Metrics configures the metrics subsystem.
// Provides MeterProvider for application metrics.
Metrics *MetricsConfig `yaml:"metrics,omitempty" json:"metrics,omitempty"`
// Propagation configures context propagation (W3C TraceContext, Baggage).
// Maps to OTEL_PROPAGATORS.
Propagation *PropConfig `yaml:"propagation,omitempty" json:"propagation,omitempty"`
// Deprecated: Use Traces.Sampling instead. Kept for backward compatibility.
Sampling *SamplingConfig `yaml:"sampling,omitempty" json:"sampling,omitempty"`
// Deprecated: Use OTLP or Traces.Exporter instead. Kept for backward compatibility.
Exporter *ExporterConfig `yaml:"exporter,omitempty" json:"exporter,omitempty"`
}
TelemetryConfig configures the OpenTelemetry system. Environment variable names follow the OTel specification: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
func LoadConfig ¶
func LoadConfig(path string) (*TelemetryConfig, error)
LoadConfig loads TelemetryConfig from a file path. It supports YAML and JSON formats. Environment variables are also parsed and override file values.
func ParseConfig ¶
func ParseConfig(data []byte) (*TelemetryConfig, error)
ParseConfig parses TelemetryConfig from a byte slice. It supports YAML and JSON formats (auto-detected). Environment variables are also parsed and override file values.
func (*TelemetryConfig) GetOTLPConfig ¶
func (c *TelemetryConfig) GetOTLPConfig() *OTLPConfig
GetOTLPConfig returns the effective OTLP config. Falls back to deprecated Exporter fields for backward compatibility.
func (*TelemetryConfig) GetOTLPEndpoint
deprecated
func (c *TelemetryConfig) GetOTLPEndpoint() string
GetOTLPEndpoint returns the effective OTLP endpoint for traces. Priority: Traces.Endpoint > the effective OTLP endpoint (GetOTLPConfig, which itself falls back to the deprecated Exporter block only when OTLP is nil); when none is set, the default follows the effective protocol (grpc → localhost:4317, otherwise localhost:4318).
It resolves through GetOTLPConfig so it can never diverge from the exporter builders — both consume the same effective OTLP block, including the non-nil-but-empty OTLP case (which intentionally does not fall back to Exporter.Endpoint).
Deprecated: the exporter builders resolve endpoints internally; this accessor is retained for API compatibility only.
func (*TelemetryConfig) GetSamplingConfig ¶
func (c *TelemetryConfig) GetSamplingConfig() *SamplingConfig
GetSamplingConfig returns the effective sampling config. Prefers Traces.Sampling, falls back to deprecated Sampling field.
func (*TelemetryConfig) GetTracesExporter ¶
func (c *TelemetryConfig) GetTracesExporter() string
GetTracesExporter returns the effective traces exporter type. Prefers Traces.Exporter, falls back to deprecated Exporter.Type.
func (*TelemetryConfig) IsEnabled ¶
func (c *TelemetryConfig) IsEnabled() bool
IsEnabled returns true if telemetry is enabled. Telemetry defaults OFF: a nil receiver or nil Enabled field reports false, so the whole telemetry system is opt-in and stays off unless Enabled is set to true. This is the opposite of TracesConfig, which defaults on once telemetry is enabled.
func (*TelemetryConfig) ValidateEndpoints ¶ added in v1.1.0
func (c *TelemetryConfig) ValidateEndpoints() error
ValidateEndpoints validates the endpoint values in the config. It is called automatically by LoadConfig and ParseConfig after struct-tag validation passes. Endpoint fields use a post-load check because the scheme rule (bare / http / https only) cannot be expressed as a built-in go-playground/validator tag.
type TracesConfig ¶
type TracesConfig struct {
// Enabled controls whether tracing is active. Defaults to true if parent is enabled.
Enabled *bool `yaml:"enabled" json:"enabled" default:"true"`
// Exporter determines the trace exporter type.
// Maps to OTEL_TRACES_EXPORTER.
// Options: "otlp", "console", "stdout", "none".
Exporter string `yaml:"exporter" json:"exporter" env:"OTEL_TRACES_EXPORTER" default:"otlp" validate:"oneof=otlp console stdout none"`
// Endpoint overrides OTLP.Endpoint for traces.
// Maps to OTEL_EXPORTER_OTLP_TRACES_ENDPOINT.
// In most cases, leave this empty and set OTLP.Endpoint instead.
// Only use this when traces need a different endpoint than other signals.
Endpoint string `yaml:"endpoint,omitempty" json:"endpoint,omitempty" env:"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"`
// Sampling configures the trace sampling strategy.
Sampling *SamplingConfig `yaml:"sampling,omitempty" json:"sampling,omitempty"`
}
TracesConfig configures the tracing subsystem.
func (*TracesConfig) IsEnabled ¶
func (c *TracesConfig) IsEnabled() bool
IsEnabled returns true if tracing is enabled. Traces default ON: a nil receiver or nil Enabled field reports true, so tracing is active whenever the parent telemetry is enabled unless explicitly disabled. This is the opposite of LogsConfig/MetricsConfig, which default off.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package carrier provides a binary-marshalable snapshot of OpenTelemetry propagation state (span context + baggage) for in-process IPC boundaries.
|
Package carrier provides a binary-marshalable snapshot of OpenTelemetry propagation state (span context + baggage) for in-process IPC boundaries. |
|
cmd
|
|
|
otlp-sim
command
Package main provides the otlp-sim CLI tool for simulating OpenTelemetry traces and logs.
|
Package main provides the otlp-sim CLI tool for simulating OpenTelemetry traces and logs. |
|
otlp-sim/engine
Package engine provides the trace/log generation engine for the OTLP simulator.
|
Package engine provides the trace/log generation engine for the OTLP simulator. |
|
otlp-sim/scenario
Package scenario defines interfaces and embedded scenarios for the OTLP simulator.
|
Package scenario defines interfaces and embedded scenarios for the OTLP simulator. |
|
Package grpc provides OpenTelemetry instrumentation for gRPC clients and servers.
|
Package grpc provides OpenTelemetry instrumentation for gRPC clients and servers. |
|
Package http provides OpenTelemetry instrumentation for HTTP clients and servers.
|
Package http provides OpenTelemetry instrumentation for HTTP clients and servers. |
|
internal
|
|
|
endpoint
Package endpoint classifies OTLP endpoint strings and provides Classify and IsHTTP helpers used by config validation, exporter.go, and zaplog/core.go.
|
Package endpoint classifies OTLP endpoint strings and provides Classify and IsHTTP helpers used by config validation, exporter.go, and zaplog/core.go. |
|
insecurewarn
Package insecurewarn emits a one-time diagnostic when telemetry would be exported as plaintext (insecure, no https:// scheme) to a non-loopback host.
|
Package insecurewarn emits a one-time diagnostic when telemetry would be exported as plaintext (insecure, no https:// scheme) to a non-loopback host. |
|
Package nats provides OpenTelemetry instrumentation for NATS JetStream.
|
Package nats provides OpenTelemetry instrumentation for NATS JetStream. |
|
Package zaplog adapts otx telemetry configuration to zapwire's OTLP log data plane (HTTP or gRPC).
|
Package zaplog adapts otx telemetry configuration to zapwire's OTLP log data plane (HTTP or gRPC). |