otx

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: Apache-2.0 Imports: 38 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.

README

OTX (OpenTelemetry Extensions)

Go Reference Go Report Card

The otx package provides a unified, configuration-driven wrapper around OpenTelemetry (OTel) for Go services. It simplifies the setup of tracing, logging, metrics, context propagation, and span management while enforcing consistent conventions.

Features

  • 🔧 Unified Configuration - Single config struct for traces, logs, and metrics with YAML/env var support
  • 🚀 Zero-Boilerplate Setup - One-line provider initialization with sensible defaults
  • 📡 Multi-Protocol Export - OTLP over gRPC or HTTP, with console/stdout options for development
  • 🔗 Automatic Context Propagation - W3C TraceContext and Baggage propagation out of the box
  • 🌐 HTTP/gRPC Middleware - Drop-in middleware for automatic request tracing
  • 📨 NATS JetStream Integration - Publisher and consumer wrappers with trace context injection
  • 📦 IPC Context Propagation - Carry span context and baggage across in-process boundaries as a compact, versioned binary blob
  • 🏷️ Semantic Conventions - Built-in helpers following OpenTelemetry naming standards
  • 🎯 Span Kind Helpers - StartServer, StartClient, StartProducer, StartConsumer for accurate service maps
  • ⚡ Baggage Utilities - Simple API for cross-service context propagation
  • 🛡️ Graceful Shutdown - Proper lifecycle management with flush-on-shutdown
  • 🧪 Testing Support - Disabled config returns ErrDisabled; callers no-op cleanly without provider setup
  • 📊 Backend Agnostic - Works with Jaeger, Zipkin, Datadog, Grafana Tempo, Honeycomb, and more

Documentation

Guide Description
Getting Started Quick 5-minute setup guide
Configuration Complete configuration reference
Semantic Conventions OpenTelemetry standards and best practices
Tracing Best Practices Patterns for effective tracing
HTTP/gRPC Integration Middleware setup and usage
NATS Integration JetStream publisher/consumer tracing
IPC OTel Carrier Carry span context + baggage across in-process boundaries as binary
Testing Testing strategies with OTX
Troubleshooting Common issues and solutions
OTLP Simulator CLI CLI tool for simulating traces and logs

Core Concepts

  • Zero-Config Defaults: Works out of the box with sensible defaults. When disabled, constructors return ErrDisabled (or signal-specific errors such as ErrTracesDisabled); guard with errors.Is(err, otx.ErrDisabled) and skip provider setup. If InitTracing is never called, otx.Start* helpers return the span already in ctx (a non-recording span when none is present).
  • Service Identity: Uses the configured ServiceName to identify the source of traces.
  • Unified Transport: Supports OTLP (gRPC/HTTP) for exporting traces to backends like Jaeger, Datadog, or Grafana Tempo.
  • Context Propagation: Automatically handles W3C TraceContext and Baggage across process boundaries.
  • Framework Agnostic: No dependency on any DI framework; integrates easily with fx, wire, or plain Go.

Installation & Setup

1. Configuration

Add the TelemetryConfig to your application's config struct:

type AppConfig struct {
    Telemetry *otx.TelemetryConfig `yaml:"telemetry"`
}

Example config.yaml:

telemetry:
  enabled: true
  serviceName: "my-service"  # OTEL_SERVICE_NAME
  environment: "production"  # OTEL_DEPLOYMENT_ENVIRONMENT
  otlp:
    endpoint: "localhost:4318"  # OTEL_EXPORTER_OTLP_ENDPOINT
    protocol: "http/protobuf"  # OTEL_EXPORTER_OTLP_PROTOCOL
  sampling:
    sampler: "parentbased_traceidratio"  # OTEL_TRACES_SAMPLER
    samplerArg: 1.0  # OTEL_TRACES_SAMPLER_ARG (sampling probability)
  propagation:
    propagators: "tracecontext,baggage"  # OTEL_PROPAGATORS
2. Direct Initialization

Initialize the providers directly in your application:

import "github.com/arloliu/otx"

func main() {
    ctx := context.Background()
    cfg := loadConfig() // your config loading logic

    // Create TracerProvider
    tp, err := otx.NewTracerProvider(ctx, cfg.Telemetry)
    if err != nil && !errors.Is(err, otx.ErrDisabled) {
        log.Fatal(err)
    }
    if tp != nil {
        defer tp.Shutdown(ctx)
        // Initialize global tracer for otx.Start() helpers
        otx.InitTracing(tp.Tracer("otx"), otx.DefaultNamer{})
    }

    // ... rest of your application
}
3. Integration with Fx

Since otx is framework-agnostic, you can define your own FxProviders in your application (e.g., in internal/config/di.go):

// FxProviders provides the OTX components to the fx application.
var FxProviders = fx.Options(
	fx.Provide(ProvideNamer),
	fx.Provide(ProvideTracerProvider),
	fx.Provide(ProvideLoggerProvider),
	fx.Provide(ProvideMeterProvider),
	fx.Provide(ProvideOTelServiceName),
)

// otelServiceNameResult is the fx output struct for ProvideOTelServiceName.
type otelServiceNameResult struct {
	fx.Out

	ServiceName string `name:"otel_service_name"`
}

// ProvideOTelServiceName extracts the service name from TelemetryConfig for use by other packages.
func ProvideOTelServiceName(cfg *otx.TelemetryConfig) otelServiceNameResult {
	return otelServiceNameResult{ServiceName: cfg.ServiceName}
}

	// ProvideNamer creates a SpanNamer.
	func ProvideNamer() otx.SpanNamer {
		return otx.DefaultNamer{}
	}

	// ProvideTracerProvider creates and registers the global TracerProvider.
	func ProvideTracerProvider(
		lc fx.Lifecycle,
		cfg *otx.TelemetryConfig,
		namer otx.SpanNamer,
	) (oteltrace.TracerProvider, error) {
		ctx := context.Background()
		tp, err := otx.NewTracerProvider(ctx, cfg)
		if err != nil {
			if errors.Is(err, otx.ErrDisabled) {
				return nil, nil
			}
			return nil, err
		}
		if tp != nil {
			otx.InitTracing(tp.Tracer("otx"), namer)
		}
		registerTracerShutdownHook(tp, lc)
		return tp, nil
	}

Usage Guide

Starting Spans

We provide helper functions to handle the boilerplate of starting spans. These automatically use the global tracer and configured naming strategy.

Helper Use Case Span Kind Interpretation
otx.Start Generic operations Internal Default block of logic
otx.StartServer Handling a request Server Inbound from queue/RPC
otx.StartClient Calling a service Client Outbound request
otx.StartInternal Background tasks Internal Cron jobs, loop processing
otx.StartProducer Publishing messages Producer Kafka/NATS publishing
otx.StartConsumer Processing messages Consumer Queue message handling

Example: Business Logic

func (s *Service) ProcessOrder(ctx context.Context, orderID string) error {
    // Starts a child span. Parent is extracted from ctx.
    ctx, span := otx.Start(ctx, "ProcessOrder")
    defer span.End()

    otx.SetAttributes(ctx, attribute.String("order.id", orderID))

    if err := s.validate(ctx, orderID); err != nil {
        // Records error and sets span status to Error
        otx.RecordError(ctx, err)
        return err
    }

    return nil
}

Example: Background Job (Root Span)

func (w *Worker) Run() {
    // Starts a NEW trace (Root Span) because ctx is background
    ctx, span := otx.StartInternal(context.Background(), "DailyCleanup")
    defer span.End()

    // ...
}
Middleware

The github.com/arloliu/otx/grpc and github.com/arloliu/otx/http packages provide drop-in wrappers for transport instrumentation. Use package aliases to avoid collisions with the stdlib grpc and http identifiers.

gRPC Middleware

The gRPC middleware wraps otelgrpc stats handlers for server and client-side tracing.

Basic Usage (uses global providers):

import (
    "google.golang.org/grpc"
    otxgrpc "github.com/arloliu/otx/grpc"
)

// Server - uses global TracerProvider, MeterProvider, and Propagator
srv := grpc.NewServer(
    grpc.StatsHandler(otxgrpc.ServerHandler()),
)

// Client - uses global providers
conn, err := grpc.NewClient(addr,
    grpc.WithStatsHandler(otxgrpc.ClientHandler()),
)

With Explicit Providers (for testing or multi-tenant scenarios):

// Server with explicit providers
srv := grpc.NewServer(
    grpc.StatsHandler(otxgrpc.ServerHandlerWithProviders(
        tracerProvider,   // trace.TracerProvider
        meterProvider,    // metric.MeterProvider
        propagator,       // propagation.TextMapPropagator
    )),
)

// Client with explicit providers
conn, err := grpc.NewClient(addr,
    grpc.WithStatsHandler(otxgrpc.ClientHandlerWithProviders(
        tracerProvider,
        meterProvider,
        propagator,
    )),
)
HTTP Middleware

Basic Usage (uses global providers):

import (
    "net/http"
    otxhttp "github.com/arloliu/otx/http"
)

// Server Middleware
http.Handle("/api", otxhttp.Middleware()(myHandler))

// Client Transport
client := &http.Client{
    Transport: otxhttp.Transport(http.DefaultTransport),
}

With Explicit Providers (for testing or multi-tenant scenarios):

// Server Middleware with explicit providers
http.Handle("/api", otxhttp.MiddlewareWithProviders(
    tracerProvider,
    meterProvider,
    propagator,
)(myHandler))

// Client Transport with explicit providers
client := &http.Client{
    Transport: otxhttp.TransportWithProviders(
        http.DefaultTransport,
        tracerProvider,
        meterProvider,
        propagator,
    ),
}
Cross-Process Context Propagation (IPC Carrier)

For network RPC between services, use W3C text propagation (gRPC/HTTP middleware above). When you instead need to carry the OTel state as an opaque blob inside your own message — a bytes field, a pipe frame, shared memory, an on-disk queue — the github.com/arloliu/otx/carrier package marshals span context and baggage to a compact, versioned binary form.

import "github.com/arloliu/otx/carrier"

// Producer: embed the OTel state in your message.
if c, ok := carrier.FromContext(ctx); ok { // ok=false when there's nothing to carry
    msg.Trace, _ = c.MarshalBinary()        // empty carrier marshals to nil
}

// Consumer: restore the trace and baggage.
if carrier.HasOTel(msg.Trace) {             // cheap pre-filter, no allocation
    var c carrier.Carrier
    if err := c.UnmarshalBinary(msg.Trace); err == nil {
        ctx = c.Context(ctx)                 // span context installed as remote parent
    } // on error: untrusted bytes, proceed without trace context
}

UnmarshalBinary treats input as hostile (bounded, panic-free, receiver unchanged on error), and the wire format is forward-compatible across otx versions. See the IPC OTel Carrier guide for the full API and semantics.

Provider Lifecycle and Shutdown

All providers (TracerProvider, LoggerProvider, MeterProvider) hold resources (connections, buffers) that must be released on application shutdown.

Shutdown Requirements
Provider Must Call Shutdown? Consequence if Not Called
TracerProvider Yes Pending spans may be lost; connections leak
LoggerProvider Yes Pending logs may be lost; connections leak
MeterProvider Yes Final metrics may be lost; connections leak

Shutdown providers in reverse order of creation to ensure all telemetry is flushed:

func main() {
    ctx := context.Background()

    // Create providers
    tp, _ := otx.NewTracerProvider(ctx, cfg)
    lp, _ := otx.NewLoggerProvider(ctx, cfg)
    mp, _ := otx.NewMeterProvider(ctx, cfg)

    // Shutdown in reverse order (LIFO)
    defer func() {
        shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()

        if mp != nil { mp.Shutdown(shutdownCtx) }
        if lp != nil { lp.Shutdown(shutdownCtx) }
        if tp != nil { tp.Shutdown(shutdownCtx) }
    }()

    // ... application code
}
Shutdown Behavior
  • Shutdown(ctx) is safe to call multiple times (idempotent)
  • Shutdown(ctx) respects the context deadline/timeout
  • After shutdown, providers become no-ops (safe but ineffective)

Best Practices

  1. Always Defer End(): Spans must be ended to be exported. defer span.End() is the safest way.
  2. Pass Context: Context is the glue. It carries the TraceID. If you break the context chain (e.g., using context.Background() inside a handler), you break the trace.
  3. Use Attributes, Not Logs: For structured data (IDs, status codes), use otx.SetAttributes. Use logs for high-volume text.
  4. Error Handling: Use otx.RecordError(ctx, err) to ensure the span is marked as failed in the monitoring UI.
  5. Mark Success: Use otx.SetSuccess(ctx) at the end of successful operations to explicitly mark the span status.
  6. Kind Matters: Use StartClient / StartServer / StartProducer / StartConsumer correctly. This helps backends generate dependency graphs (Service Map).
  7. Access Current Span: Use otx.SpanFromContext(ctx) to get the current span for advanced operations.
  8. Always Shutdown Providers: Call Shutdown(ctx) on all providers before application exit to flush pending telemetry.
Span Naming Best Practices

Based on conventions from Kubernetes, OpenTelemetry Contrib, gRPC-Go, Jaeger, and go-kit:

Category Convention Examples
HTTP Server METHOD /route GET /users/{id}, POST /api/orders
HTTP Client METHOD or METHOD /path GET, POST /api/users
gRPC Server package.Service/Method myapp.OrderService/CreateOrder
gRPC Client package.Service/Method payment.PaymentService/Charge
Database operation table or collection.operation SELECT users, orders.find
Messaging operation destination publish orders.created, receive ORDERS
Cloud SDK Service.Operation S3.GetObject, DynamoDB.PutItem
Internal Descriptive name ProcessOrder, validate.input

Key Principles:

  • Low cardinality: Use route templates (/users/{id}) not actual paths (/users/12345)
  • Include HTTP method: GET /users not just /users
  • Use consistent delimiters: Dots for packages, slashes for routes
  • Be descriptive but concise: findTraceIDs over find or findTraceIDsFromDatabaseByServiceName

Troubleshooting

  • "My traces are disconnected!": Check if you are passing ctx correctly through all functions. Ensure you aren't using context.TODO() or context.Background() mid-flow.
  • "No traces appear":
    • Check OTX_ENABLED=true.
    • Check OTEL_EXPORTER_OTLP_ENDPOINT is reachable.
    • Check logs for otx errors (initialization failures).
  • "Timestamps are wrong": Ensure system clocks are synchronized, especially in distributed environments.
Environment Variables

All configuration options can be set via environment variables. OTX follows the OpenTelemetry Environment Variable Specification.

Variable Description Default
OTX_ENABLED Enable/disable OTX telemetry system false
OTEL_SERVICE_NAME Service name for telemetry identification (required if enabled)
OTEL_SERVICE_VERSION Service version (e.g., git commit, semver) -
OTEL_DEPLOYMENT_ENVIRONMENT Deployment environment (production, development) development
OTEL_RESOURCE_ATTRIBUTES Additional resource attributes (comma-separated key=value) -
OTEL_EXPORTER_OTLP_ENDPOINT OTLP collector endpoint localhost:4318
OTEL_EXPORTER_OTLP_PROTOCOL OTLP protocol: grpc, http/protobuf, http http/protobuf
OTEL_EXPORTER_OTLP_HEADERS Custom headers (comma-separated key=value) -
OTEL_EXPORTER_OTLP_TIMEOUT Exporter timeout 10s
OTEL_EXPORTER_OTLP_INSECURE Disable TLS for OTLP connection true
OTEL_EXPORTER_OTLP_COMPRESSION Compression: gzip, none -
OTEL_TRACES_EXPORTER Trace exporter: otlp, console, stdout, none otlp
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT Override endpoint for traces only -
OTEL_TRACES_SAMPLER Sampler type (see below) parentbased_always_on
OTEL_TRACES_SAMPLER_ARG Sampler argument (ratio 0.0-1.0) 1.0
OTEL_LOGS_EXPORTER Log exporter: otlp, console, stdout, none otlp
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT Override endpoint for logs only -
OTEL_METRICS_EXPORTER Metrics exporter: otlp, console, stdout, none otlp
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT Override endpoint for metrics only -
OTEL_METRIC_EXPORT_INTERVAL Metrics export interval 60s
OTEL_PROPAGATORS Context propagators (comma-separated) tracecontext,baggage

Sampler Types (OTEL_TRACES_SAMPLER):

  • always_on - Sample all traces
  • always_off - Sample no traces
  • traceidratio - Sample based on trace ID ratio
  • parentbased_always_on - Parent-based with always_on root (default)
  • parentbased_always_off - Parent-based with always_off root
  • parentbased_traceidratio - Parent-based with ratio root

Propagator Types (OTEL_PROPAGATORS):

  • tracecontext - W3C Trace Context
  • baggage - W3C Baggage
  • b3, b3multi - Zipkin B3 (requires contrib package)
  • jaeger, xray, ottrace - Other formats (require contrib packages)

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

Constants

This section is empty.

Variables

View Source
var ErrDisabled = errors.New("otx: telemetry is disabled")

ErrDisabled is returned when telemetry is disabled.

View Source
var ErrLogsDisabled = errors.New("otx: logs export is disabled")

ErrLogsDisabled is returned when log export is disabled.

View Source
var ErrMetricsDisabled = errors.New("otx: metrics export is disabled")

ErrMetricsDisabled is returned when metrics export is disabled.

View Source
var ErrServiceNameRequired = errors.New("otx: service name is required")

ErrServiceNameRequired is returned when ServiceName is empty but telemetry is enabled.

View Source
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.

View Source
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 AddEvent

func AddEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)

AddEvent adds an event to the current span.

func AllBaggage

func AllBaggage(ctx context.Context) map[string]string

AllBaggage returns all baggage members as a map.

func BoolPtr added in v1.1.0

func BoolPtr(v bool) *bool

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

func BuildResource(ctx context.Context, cfg *TelemetryConfig) (*resource.Resource, error)

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

func DeleteBaggage(ctx context.Context, key string) context.Context

DeleteBaggage removes a key from baggage in the context.

func ExtractGRPC

func ExtractGRPC(ctx context.Context, md metadata.MD) context.Context

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

func ExtractHTTP(ctx context.Context, headers http.Header) context.Context

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

func GetBaggage(ctx context.Context, key string) string

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

func InitTracing(tracer trace.Tracer, namer SpanNamer)

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

func InjectGRPC(ctx context.Context, md metadata.MD)

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

func InjectHTTP(ctx context.Context, headers http.Header)

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

func LookupBaggage(ctx context.Context, key string) (string, bool)

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

func MustSetBaggage(ctx context.Context, key, value string) context.Context

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

func NameDB(verb, table string) string

NameDB returns a compliant span name for a database operation: "verb table". Example: "SELECT users"

func NameHTTP

func NameHTTP(method, route string) string

NameHTTP returns a compliant span name for an HTTP request: "METHOD /route". Example: "GET /users/{id}"

func NameMessaging

func NameMessaging(verb, destination string) string

NameMessaging returns a compliant span name for a messaging operation: "verb destination". Example: "publish orders"

func NameRPC

func NameRPC(service, method string) string

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

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

SetAttributes sets attributes on the current span.

func SetBaggage

func SetBaggage(ctx context.Context, key, value string) (context.Context, error)

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

func SetSuccess(ctx context.Context)

SetSuccess marks the current span as successful.

func Span deprecated

func Span(ctx context.Context) trace.Span

Span returns the current span from context.

Deprecated: use SpanFromContext instead.

func SpanFromContext

func SpanFromContext(ctx context.Context) trace.Span

SpanFromContext retrieves the current span from the context.

func SpanID

func SpanID(ctx context.Context) string

SpanID returns the span ID from context, or empty string if none.

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).

func StartServer

func StartServer(ctx context.Context, operation string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartServer begins a new server span (e.g., handling an incoming request).

func TraceID

func TraceID(ctx context.Context) string

TraceID returns the trace ID from context, or empty string if none.

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 SpanNamer

type SpanNamer interface {
	Name(operation string) string
}

SpanNamer defines how operation names are transformed into span names.

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.

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).

Jump to

Keyboard shortcuts

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