otel

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package otel bootstraps OpenTelemetry tracing and provides helpers to inject a trace id into the context (and therefore into logs), open child spans, and propagate trace context across service boundaries.

InitTracing wires a global TracerProvider that exports spans over OTLP/gRPC and samples with a parent-based ratio sampler that always drops excluded routes (health/readiness probes) and anything started from a suppressed context (see Suppress). InjectTracing seeds the request context with the tracer and a guaranteed trace id, so GetTraceID — usable directly as logger.TraceIDFn — makes every log line carry the active trace.

Startup

Initialize once and defer the returned shutdown to flush pending spans:

tracer, shutdown, err := otel.InitTracing(ctx, otel.Config{
	ServiceName:    "myapp",
	Endpoint:       "localhost:4317",
	Insecure:       true,
	Probability:    0.1,
	ExcludedRoutes: map[string]struct{}{"/healthz": {}, "/readyz": {}},
})
if err != nil {
	return err
}
defer shutdown(context.Background())

log := logger.New(os.Stdout, logger.Config{
	Service: "myapp", TraceIDFn: otel.GetTraceID, // every line gets trace_id
})

Per request

Call InjectTracing once before handling so a trace id is always present, then open child spans on the tracer carried by the context:

ctx = otel.InjectTracing(r.Context(), tracer)
ctx, span := otel.AddSpan(ctx, "load-widget", attribute.String("id", id))
defer span.End()

AddSpan returns a no-op span when no tracer is in ctx, so callers never need a nil check.

Suppressing background traces

Background tick loops — pollers, outbox relays, sweepers, cleaners — run every few seconds with no request behind them, so each poll query exports its own single-span trace and buries the traces that describe real traffic. Wrap the tick context in Suppress and the sampler drops those spans outright:

ctx = otel.Suppress(ctx)                 // once per tick
rows, err := store.LeasePending(ctx)     // no span exported

Suppression is inherited by every derived context, so nothing below the tick is traced either. When a tick finds work worth tracing, start that span from context.Background() instead of from the suppressed context. Re-inject the tracer, since it travels in the context too:

rowCtx := otel.InjectTracing(context.Background(), tracer)
rowCtx, span := otel.AddSpan(rowCtx, "dispatch-row")

AddSpan takes no span links; to associate the new root with the tick, start it on the tracer directly with trace.WithLinks(trace.LinkFromContext(ctx)).

Note that re-rooting also detaches cancellation: derive a fresh context.WithTimeout (or check the tick's ctx.Err() between rows) so shutdown still stops the loop.

Propagation

Carry trace context across boundaries with the W3C propagator. For HTTP, use InjectToRequest on the caller and ExtractFromRequest on the callee. For out-of-band transports (e.g. an outbox event's headers), Carrier serializes the context to a string map and ExtractFromCarrier restores it:

otel.InjectToRequest(ctx, req)              // outgoing HTTP
ctx = otel.ExtractFromRequest(ctx, r)       // incoming HTTP

headers := otel.Carrier(ctx)                // store on a message
ctx = otel.ExtractFromCarrier(ctx, headers) // restore in a consumer

Config

Config fields for InitTracing:

  • ServiceName: tags every span and names the returned Tracer.
  • Endpoint: OTLP/gRPC collector endpoint, e.g. "localhost:4317".
  • Insecure: disable TLS to the collector (local/in-cluster).
  • Probability: sampling ratio in [0,1] for non-excluded routes.
  • ExcludedRoutes: route names that are never sampled (probes, etc.); the route is read from the span name set by HTTP middleware.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSpan

func AddSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span)

AddSpan starts a child span on the tracer stored in ctx. If no tracer is present it returns ctx unchanged and a no-op span, so callers never need a nil check.

func AddSpanAt added in v0.6.0

func AddSpanAt(ctx context.Context, name string, start, end time.Time, attrs ...attribute.KeyValue) (context.Context, trace.Span)

AddSpanAt starts AND ends a span with explicit start/end timestamps — a BACKDATED span — for reconstructing already-finished operations whose real times are known (e.g. replaying techlog/audit records into a trace). It returns the child context, so nested backdated spans can be parented to it, and the (already ended) span. With no tracer in ctx it is a no-op returning ctx and the current span, so callers never need a nil check.

func Carrier

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

Carrier returns the W3C trace context (traceparent/tracestate) and baggage carried by ctx as a string map, using the configured propagator. It is the transport-agnostic counterpart to InjectToRequest: store the map on a message (e.g. an outbox event's headers) so a consumer can extract it with ExtractFromCarrier and continue the trace. Returns nil when ctx carries no propagatable context.

func ExtractFromCarrier

func ExtractFromCarrier(ctx context.Context, carrier map[string]string) context.Context

ExtractFromCarrier returns a context seeded with the trace context held in a string map produced by Carrier — the inverse of Carrier, for consumers that receive trace headers out of band (e.g. from a broker message).

func ExtractFromRequest

func ExtractFromRequest(ctx context.Context, r *http.Request) context.Context

ExtractFromRequest returns a context seeded with the trace context carried by an incoming request's headers.

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID returns the trace id stored in ctx, or an empty string if none. It is designed to be passed as logger.TraceIDFn so every log line carries the active trace id.

func InitTracing

func InitTracing(ctx context.Context, cfg Config) (trace.Tracer, func(context.Context) error, error)

InitTracing configures a global TracerProvider exporting via OTLP/gRPC and returns a Tracer plus a shutdown function. The shutdown flushes pending spans.

func InjectToRequest

func InjectToRequest(ctx context.Context, r *http.Request)

InjectToRequest writes the current trace context into an outgoing request's headers so the callee can continue the trace.

func InjectTracing

func InjectTracing(ctx context.Context, tracer trace.Tracer) context.Context

InjectTracing stores the tracer in ctx and ensures a trace id is available (generating one when there is no active span), so downstream logging can pick it up via GetTraceID. Call it once per request, before handling.

func IsSuppressed added in v0.10.0

func IsSuppressed(ctx context.Context) bool

IsSuppressed reports whether ctx, or any context it was derived from, went through Suppress. A nil context is not suppressed.

func Suppress added in v0.10.0

func Suppress(ctx context.Context) context.Context

Suppress marks ctx as "do not trace anything started from here". Spans started with a suppressed context — and their children — are dropped by the sampler InitTracing installs: they are neither recorded nor exported, so the cost is one context value and one no-op span object per call.

Intended for background tick loops (pollers, outbox relays, sweepers, cleaners). Their poll/lease/cleanup queries fire every few seconds, carry no parent span, and would each surface in the trace UI as a separate single-span trace — thousands a day of "SELECT … FOR UPDATE SKIP LOCKED returned nothing", crowding out the traces that describe real traffic.

Suppression is inherited by every context derived from a suppressed one, so nothing below the tick is traced either. When a tick does find work worth tracing, start that span from context.Background() (carrying the tick's span context as a link if there is one) rather than deriving it from the suppressed context — see the "Suppressing background traces" section of the package doc.

Deliberately explicit at the call site: a name-based rule in the sampler ("drop parentless postgres: … spans") looks equivalent but goes silently stale the moment a span is renamed, and it also erases the only traces one-shot CLI commands produce, since none of them opens a root span.

Types

type Config

type Config struct {
	// ServiceName tags every span; also used to create the named Tracer.
	ServiceName string
	// Endpoint is the OTLP/gRPC collector endpoint, e.g. "localhost:4317".
	Endpoint string
	// Insecure disables TLS to the collector (typical for local/in-cluster).
	Insecure bool
	// Probability is the sampling ratio in [0,1] applied to non-excluded routes.
	Probability float64
	// ExcludedRoutes are never sampled (health/readiness probes, etc.).
	ExcludedRoutes map[string]struct{}
}

Config configures tracing.

Jump to

Keyboard shortcuts

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