otel

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 10 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). 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.

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 Carrier added in v0.5.0

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 added in v0.5.0

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.

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