otel

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package otel is the OpenTelemetry API of skit: tracers for SDK packages, span errors, suppression of background traces and W3C trace context propagation. It imports only the OpenTelemetry API; the SDK, the Resource and the exporter are installed by otel/setup and otel/otlp.

Tracers

An SDK component takes a trace.TracerProvider in its Config and gets its tracer once, in the constructor. The scope is the package import path; nil means the global provider:

type Config struct {
	TracerProvider trace.TracerProvider // nil → global
}

func New(cfg Config) *Publisher {
	return &Publisher{tracer: otel.Tracer(cfg.TracerProvider, "github.com/assanoff/skit/broker/rabbitmq")}
}

Spans are opened with tracer.Start. Neither the tracer nor the provider travels in the context: the context carries only the span context.

Errors

SetError marks a span as failed with status Error and error.type, taken from an ErrorType() string method in the error chain:

ctx, span := s.tracer.Start(ctx, "load")
defer span.End()
if err := s.load(ctx); err != nil {
	otel.SetError(span, err)
	return err
}

The details of the error belong to the log record with the "err" key; skit does not call span.RecordError.

Suppressing background traces

Background tick loops — pollers, queue workers, cleaners — run every few seconds with no request behind them, so each poll query would export its own single-span trace and bury 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.Claim(ctx) // no span exported

Suppression is inherited by every derived context. When the tick finds work worth tracing, lift it for that work and continue the item's own trace:

itemCtx := otel.ExtractFromCarrier(otel.Unsuppress(ctx), row.Headers)
itemCtx, span := tracer.Start(itemCtx, "dispatch")

Propagation

Propagator is W3C TraceContext only: baggage never leaves the process. For out-of-band transports (e.g. the envelope of an outbox event), Carrier serializes the trace context to a string map and ExtractFromCarrier restores it:

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

InjectToResponse writes the traceparent of the request's server span into the response headers, so a client can find the trace by the response.

Example

A component takes its tracer once, from the provider of its Config, with its import path as the scope. SetError marks a failed span: status Error and error.type, here the code of an *errs.Error.

package main

import (
	"context"
	"fmt"
	"log/slog"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"

	"github.com/assanoff/skit/errs"
	"github.com/assanoff/skit/otel"
	"github.com/assanoff/skit/otel/setup"
)

// keepSpans is the exporter in memory of the OTel SDK, but its spans outlive
// Shutdown, which flushes them.
type keepSpans struct {
	*tracetest.InMemoryExporter
}

func (keepSpans) Shutdown(context.Context) error { return nil }

// newTelemetry installs the SDK as a process does, with an exporter in memory
// in place of OTLP.
func newTelemetry(exp sdktrace.SpanExporter) (*setup.Telemetry, error) {
	return setup.New(context.Background(), slog.New(slog.DiscardHandler), setup.Config{
		Service:  "orders",
		Exporter: exp,
		Sampler:  sdktrace.AlwaysSample(),
	})
}

func main() {
	exp := keepSpans{tracetest.NewInMemoryExporter()}
	tel, err := newTelemetry(exp)
	if err != nil {
		fmt.Println(err)
		return
	}
	tracer := otel.Tracer(tel.TracerProvider(), "example.com/orders/store")

	_, span := tracer.Start(context.Background(), "load order")
	otel.SetError(span, errs.Newf(errs.NotFound, "order 42 not found"))
	span.End()

	if err := tel.Shutdown(); err != nil { // flushes the spans
		fmt.Println(err)
		return
	}
	for _, s := range exp.GetSpans() {
		fmt.Println(s.Name, s.InstrumentationScope.Name)
		fmt.Println(s.Status.Code) // the error text is the Description
		for _, a := range s.Attributes {
			fmt.Println(a.Key, a.Value.String())
		}
	}
}
Output:
load order example.com/orders/store
Error
error.type not_found

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Carrier

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

Carrier returns the trace context carried by ctx as a string map. Store the map on a message (e.g. an outbox event's headers) so a consumer can restore it with ExtractFromCarrier and continue the trace. Returns nil when ctx carries no span context.

Example

Carrier puts the trace context on a message, such as the headers of an outbox event; the consumer restores it with ExtractFromCarrier and its spans continue the trace.

package main

import (
	"context"
	"fmt"

	"go.opentelemetry.io/otel/trace"

	"github.com/assanoff/skit/otel"
)

func main() {
	traceID, err := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	if err != nil {
		fmt.Println(err)
		return
	}
	spanID, err := trace.SpanIDFromHex("00f067aa0ba902b7")
	if err != nil {
		fmt.Println(err)
		return
	}
	ctx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(
		trace.SpanContextConfig{TraceID: traceID, SpanID: spanID, TraceFlags: trace.FlagsSampled}))

	headers := otel.Carrier(ctx)
	fmt.Println(headers)

	sc := trace.SpanContextFromContext(otel.ExtractFromCarrier(context.Background(), headers))
	fmt.Println(sc.TraceID(), sc.SpanID(), sc.IsRemote())
}
Output:
map[traceparent:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01]
4bf92f3577b34da6a3ce929d0e0e4736 00f067aa0ba902b7 true

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

func InjectToResponse(ctx context.Context, h http.Header)

InjectToResponse writes the trace context of the request's own span — the server span this process opened — into the response headers as W3C traceparent / tracestate, so a client or QA can find the trace by the response. It writes nothing when ctx carries no span of this process: a remote parent extracted from the request is the caller's span, and echoing it back would point at the wrong span. Call it before the handler writes the status line.

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

func Propagator() propagation.TextMapPropagator

Propagator returns the propagator skit uses on every boundary: W3C TraceContext (traceparent, tracestate) and nothing else. Baggage is not propagated, so it never reaches third parties, outbox rows or the broker. otelhttp and otelgrpc get it explicitly; otel/setup also installs it as the global propagator for third-party libraries.

func SetError added in v0.14.0

func SetError(span trace.Span, err error)

SetError marks span as failed: status Error with the error text and error.type. error.type comes from an ErrorType() string method anywhere in the err chain, else from the error's type. A nil err does nothing.

The exception details belong to the log record written with the "err" key, not to the span: SetError replaces span.RecordError.

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 otel/setup installs: they are neither recorded nor exported, so the cost is one context value and one non-recording span per call.

Intended for background tick loops (pollers, queue workers, 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, lift it for that work with Unsuppress — 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.

Example

A background tick runs under Suppress, so the sampler of otel/setup drops its spans; the work the tick finds is traced after Unsuppress.

package main

import (
	"context"
	"fmt"
	"log/slog"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"

	"github.com/assanoff/skit/otel"
	"github.com/assanoff/skit/otel/setup"
)

// keepSpans is the exporter in memory of the OTel SDK, but its spans outlive
// Shutdown, which flushes them.
type keepSpans struct {
	*tracetest.InMemoryExporter
}

func (keepSpans) Shutdown(context.Context) error { return nil }

// newTelemetry installs the SDK as a process does, with an exporter in memory
// in place of OTLP.
func newTelemetry(exp sdktrace.SpanExporter) (*setup.Telemetry, error) {
	return setup.New(context.Background(), slog.New(slog.DiscardHandler), setup.Config{
		Service:  "orders",
		Exporter: exp,
		Sampler:  sdktrace.AlwaysSample(),
	})
}

func main() {
	exp := keepSpans{tracetest.NewInMemoryExporter()}
	tel, err := newTelemetry(exp)
	if err != nil {
		fmt.Println(err)
		return
	}
	tracer := otel.Tracer(tel.TracerProvider(), "example.com/orders/poller")

	tick := otel.Suppress(context.Background())
	_, poll := tracer.Start(tick, "claim jobs")
	poll.End()
	_, job := tracer.Start(otel.Unsuppress(tick), "send receipt")
	job.End()

	if err := tel.Shutdown(); err != nil {
		fmt.Println(err)
		return
	}
	for _, s := range exp.GetSpans() {
		fmt.Println(s.Name)
	}
	fmt.Println(otel.IsSuppressed(tick))
}
Output:
send receipt
true

func Tracer added in v0.14.0

func Tracer(tp trace.TracerProvider, scope string) trace.Tracer

Tracer returns the tracer an SDK package records its spans with. scope is the package import path; the tracer carries the skit module version and the semconv schema URL. A nil tp means the global provider: a tracer taken from it before the SDK is installed switches to the SDK once it is, so a component takes its tracer once, in its constructor.

func Unsuppress added in v0.14.0

func Unsuppress(ctx context.Context) context.Context

Unsuppress lifts Suppress for ctx and the contexts derived from it. A tick calls it for each item worth tracing, together with the item's own trace context (ExtractFromCarrier) or trace.WithNewRoot. The sampler sees the parent context with all its values even for a new root, so the mark must be lifted rather than left behind.

Types

This section is empty.

Directories

Path Synopsis
Package otlp builds the OTLP/gRPC span exporter for otel/setup.
Package otlp builds the OTLP/gRPC span exporter for otel/setup.
Package setup installs the OpenTelemetry SDK of a process: the TracerProvider, the Resource, the sampler, the propagator and the OTel diagnostics.
Package setup installs the OpenTelemetry SDK of a process: the TracerProvider, the Resource, the sampler, the propagator and the OTel diagnostics.

Jump to

Keyboard shortcuts

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