setup

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package setup installs the OpenTelemetry SDK of a process: the TracerProvider, the Resource, the sampler, the propagator and the OTel diagnostics. It does not import gRPC; the OTLP exporter comes from otel/otlp. SDK packages never import setup: they take a trace.TracerProvider in their Config.

Usage

Build it first among the dependencies, so it is closed last and the spans of the stopping servers are flushed:

exp, err := otlp.NewExporter(ctx) // nil when OTEL_TRACES_EXPORTER=none
if err != nil {
	return err
}
tel, err := setup.New(ctx, log, setup.Config{
	Service:     "orders",
	Version:     version,
	Environment: "production",
	Exporter:    exp,
	Metrics:     reg,
	Global:      true,
})
if err != nil {
	return err
}
defer tel.Shutdown()
srv := grpcserver.New(log, grpcserver.Config{TracerProvider: tel.TracerProvider()})

Trace context without export

The SDK provider is installed even when nothing is exported. With a nil Exporter no span is sampled, but every root still gets a W3C trace id: log records carry it and outgoing calls propagate it with trace flags 00.

Sampling

OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG choose the sampler with the values and defaults of the OpenTelemetry specification: always_on, always_off, traceidratio and their parentbased_ forms; unset means parentbased_always_on, and the ratio defaults to 1.0. setup reads them itself, because the Suppress wrapper replaces the SDK's own reading. An unsupported value is logged at WARN and the default is used.

otel.Suppress applies on top of any sampler: a span started from a suppressed context is dropped, and otel.Unsuppress lifts the mark.

A fleet keeps one ratio for all services: with traceidratio a service samples independently of its callers, and equal ratios keep traces whole between Go services.

Resource

The Resource holds telemetry.sdk.*, host.name, service.instance.id, the attributes from OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES, and the non-empty Config fields, which win over the environment: service.name, service.version, service.namespace and deployment.environment.name — the values the log records carry.

Diagnostics

With Global, OTel's errors (a failed export, an invalid attribute) and its internal logger write to the given *slog.Logger: errors and warnings at WARN, the rest at DEBUG. Nothing goes to stderr as plain text, and a failing collector never reaches ERROR.

Metrics

With a registry in Config.Metrics, New sets target_info to 1, labeled with every attribute of the Resource under its Prometheus name (service.name → service_name, k8s.pod.name → k8s_pod_name): a dashboard sees which service, version and environment run in each target and joins the metrics to the traces by service_name. It also counts the spans passed to the Exporter in skit_otel_exported_spans_total by result (ok, error); without an Exporter the counter does not exist. Spans the batcher drops on a full queue never reach the exporter and are not counted; they pile up when exports fail, which result="error" shows. Build the registry before setup, so the process exposes these next to its own metrics.

Config

  • Service, Version, Namespace, Environment: the identity of the process; empty fields are not written.
  • Sampler: overrides the sampler from the environment; tests set it.
  • Exporter: otlp.NewExporter in a process, tracetest in tests; nil → no export. Shutdown flushes the spans to the exporter and shuts it down, and tracetest.InMemoryExporter forgets its spans then: the example keeps them behind a Shutdown of its own.
  • Metrics: the registry for target_info and skit_otel_*; nil → no metrics. Tests leave it nil.
  • Global: install the provider, the propagator (W3C TraceContext only) and the diagnostics process-wide; true in a process, false in tests.
  • ShutdownTimeout: bound for Shutdown; 0 → 5s.
Example

New installs the SDK: the provider sends the sampled spans to the Exporter, each with the Resource of the process, and Shutdown flushes them. A process takes the exporter from otel/otlp and sets Global; an exporter in memory stands in for it here.

package main

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

	"go.opentelemetry.io/otel/attribute"

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

	"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 }

func main() {
	exp := keepSpans{tracetest.NewInMemoryExporter()}
	tel, err := setup.New(context.Background(), slog.New(slog.DiscardHandler), setup.Config{
		Service:     "orders",
		Version:     "1.4.0",
		Environment: "staging",
		Exporter:    exp,
		Sampler:     sdktrace.AlwaysSample(),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	_, span := tel.TracerProvider().Tracer("example.com/orders").Start(context.Background(), "checkout")
	span.End()
	fmt.Println("shutdown:", tel.Shutdown())

	for _, s := range exp.GetSpans() {
		fmt.Println(s.Name, s.SpanContext.IsSampled())
		for _, key := range []string{"service.name", "service.version", "deployment.environment.name"} {
			v, _ := s.Resource.Set().Value(attribute.Key(key))
			fmt.Println(key, v.String())
		}
	}
}
Output:
shutdown: <nil>
checkout true
service.name orders
service.version 1.4.0
deployment.environment.name staging
Example (Metrics)

With a registry, target_info names the process and skit_otel_exported_spans_total counts the spans passed to the exporter.

package main

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

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"

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

	"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 }

func main() {
	reg := prometheus.NewRegistry()
	tel, err := setup.New(context.Background(), slog.New(slog.DiscardHandler), setup.Config{
		Service:  "orders",
		Exporter: keepSpans{tracetest.NewInMemoryExporter()},
		Sampler:  sdktrace.AlwaysSample(),
		Metrics:  reg,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, name := range []string{"checkout", "pay"} {
		_, span := tel.TracerProvider().Tracer("example.com/orders").Start(context.Background(), name)
		span.End()
	}
	if err := tel.Shutdown(); err != nil {
		fmt.Println(err)
		return
	}

	mfs, err := reg.Gather()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, mf := range mfs {
		for _, m := range mf.GetMetric() {
			switch mf.GetName() {
			case "skit_otel_exported_spans_total":
				fmt.Println(mf.GetName(), "result="+label(m, "result"), m.GetCounter().GetValue())
			case "target_info":
				fmt.Println(mf.GetName(), "service_name="+label(m, "service_name"), m.GetGauge().GetValue())
			}
		}
	}
}

// label returns the value of the label name of m, or "".
func label(m *dto.Metric, name string) string {
	for _, l := range m.GetLabel() {
		if l.GetName() == name {
			return l.GetValue()
		}
	}
	return ""
}
Output:
skit_otel_exported_spans_total result=error 0
skit_otel_exported_spans_total result=ok 2
target_info service_name=orders 1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Service is service.name. Empty → OTEL_SERVICE_NAME, then the SDK's
	// unknown_service:<executable>.
	Service string
	// Version is service.version.
	Version string
	// Namespace is service.namespace.
	Namespace string
	// Environment is deployment.environment.name.
	Environment string
	// Sampler decides which spans are recorded; Suppress applies on top of it.
	// nil → OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG. Tests set it.
	Sampler sdktrace.Sampler
	// Exporter receives the sampled spans: otlp.NewExporter in a process,
	// tracetest in tests. nil → no span is sampled or exported; trace ids are
	// still created and propagated.
	Exporter sdktrace.SpanExporter
	// Metrics is the registry for target_info and skit_otel_*; nil — metrics
	// off.
	Metrics prometheus.Registerer
	// Global installs the provider, the propagator and the OTel error handler
	// and logger process-wide: true in a process, false in tests.
	Global bool
	// ShutdownTimeout bounds Shutdown; 0 → 5s.
	ShutdownTimeout time.Duration
}

Config configures the telemetry of a process.

type Telemetry

type Telemetry struct {
	// contains filtered or unexported fields
}

Telemetry is the OpenTelemetry SDK of a process.

func New

func New(ctx context.Context, log *slog.Logger, cfg Config) (*Telemetry, error)

New builds the Resource and the SDK TracerProvider. log receives the OTel diagnostics, never above WARN: a failing collector must not wake the ERROR hooks.

func (*Telemetry) Resource

func (t *Telemetry) Resource() *resource.Resource

Resource returns the Resource the spans carry.

func (*Telemetry) Shutdown

func (t *Telemetry) Shutdown() error

Shutdown flushes the pending spans and stops the exporter within Config.ShutdownTimeout. It does not take the caller's context: shutdown starts after a signal canceled it. It is a dim.CleanupFunc.

func (*Telemetry) TracerProvider

func (t *Telemetry) TracerProvider() trace.TracerProvider

TracerProvider returns the SDK provider for the Config of components.

Jump to

Keyboard shortcuts

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