telemetry

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 23 Imported by: 0

README

telemetry

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

telemetry is a vendor-neutral OpenTelemetry runtime for Go services. It owns resource identity, trace and metric providers, OTLP exporters, propagation, sampling, global registration, flush, and shutdown while returning the standard OpenTelemetry APIs.

The package targets an OpenTelemetry Collector. It does not wrap vendor SDKs, replace OpenTelemetry types, read configuration implicitly, or add log-signal stability promises.

Requirements

  • Go 1.25 or 1.26
  • OpenTelemetry Go 1.43.x or 1.44.x
  • an OTLP-compatible Collector for production export

Quick start

package main

import (
	"context"
	"log"

	telemetry "github.com/faustbrian/go-telemetry"
)

func main() {
	config := telemetry.DefaultConfig("orders", "1.2.3")
	config.Environment = "production"
	config.Traces.Exporter.Endpoint = "otel-collector:4317"
	config.Metrics.Exporter.Endpoint = "otel-collector:4317"

	runtime, err := telemetry.Init(context.Background(), config)
	if err != nil {
		log.Fatal(err)
	}

	ctx, span := runtime.Tracer("orders").Start(context.Background(), "orders.list")
	defer span.End()
	_ = ctx

	if err := runtime.Shutdown(context.Background()); err != nil {
		log.Fatal(err)
	}
}

DefaultConfig only builds a value. Network clients, providers, globals, and goroutines are created by Init. Runtime exposes standard tracer, meter, and propagator interfaces. Shutdown is idempotent, bounded by the configured timeout, restores only globals still owned by the runtime, and joins provider and exporter failures.

Safe defaults

Setting Default
signals traces and metrics enabled
transport OTLP/gRPC to localhost:4317
transport security explicit insecure local Collector connection
compression gzip
trace sampling parent-based 10% ratio
span queue / batch 2,048 / 512
metric cardinality 1,000 points per instrument
baggage disabled
shutdown timeout 10 seconds

Every default is represented in Config and can be inspected or overridden. Production clusters should configure TLS or deliberately retain an authenticated cluster-local insecure connection.

Packages

  • root: configuration, resources, provider lifecycle, globals, and errors
  • otlp: explicit OTLP/gRPC and OTLP/HTTP exporter construction
  • trace: always-on, always-off, ratio, and parent-based samplers
  • metric: views, histogram boundaries, attribute allow-lists, and cardinality
  • propagation: bounded W3C trace context and trusted baggage policies
  • instrumentation/nethttp: private-by-default net/http server and client
  • instrumentation/gohttpclient: http-client RoundTripper adapter
  • instrumentation/gopostgres: pgx query tracer for postgres
  • instrumentation/gocache: dependency-neutral cache observations
  • instrumentation/goqueue: dependency-neutral queue handler wrapper
  • telemetryservice: explicit service lifecycle initialization and shutdown
  • testtelemetry: deterministic in-memory providers and snapshots

Instrumentation never records raw URL paths, queries, hosts, headers, client addresses, SQL, query arguments, database error text, cache keys or values, queue messages, raw handler errors, or panic values by default.

Service lifecycle

telemetryservice.New constructs and owns a runtime as a service.Component. Callers explicitly choose required or best-effort initialization and retain control of Config.RegisterGlobal, exporters, sampling, and propagation. The adapter exposes the concrete runtime, performs no retries, and delegates bounded flush, shutdown, and global restoration to Runtime.Shutdown.

Required initialization failures stop service startup. Best-effort failures permit startup and remain available through InitializationError; no readiness check is added because telemetry availability does not determine whether the service can accept business work.

Documentation

Start with the documentation index for the public contract, architecture, compatibility, upgrade, contribution, and security material.

Runnable commands are in examples/service and examples/worker.

Development

make check
make race
make fuzz
make benchmark

CI also runs linting, vulnerability scanning, examples, Collector protocol tests, and the supported Go/OpenTelemetry matrix. Library packages enforce meaningful 100% statement coverage.

Stability

Trace and metric APIs use stable OpenTelemetry interfaces. The log signal is intentionally absent from the stable runtime; see log stability. Major releases may refine configuration, but changes are documented in CHANGELOG.md and follow semantic versioning.

License

MIT. See LICENSE.

Documentation

Overview

Package telemetry provides an explicit, vendor-neutral OpenTelemetry runtime.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAlreadyInitialized indicates that a globally registered runtime is
	// already active in this process.
	ErrAlreadyInitialized = errors.New("telemetry runtime already initialized")
)

Functions

func BuildResource

func BuildResource(ctx context.Context, config Config) (*resource.Resource, error)

BuildResource constructs the resource used by every enabled signal. Service identity always wins over custom attributes.

Types

type BatchConfig

type BatchConfig struct {
	MaxQueueSize       int
	MaxExportBatchSize int
	BatchTimeout       time.Duration
	ExportTimeout      time.Duration
}

BatchConfig bounds trace batching and its memory use.

type Compression

type Compression string

Compression selects exporter payload compression.

const (
	// CompressionNone disables payload compression.
	CompressionNone Compression = "none"
	// CompressionGZIP enables gzip payload compression.
	CompressionGZIP Compression = "gzip"
)

type Config

type Config struct {
	Service         ServiceConfig
	Environment     string
	Resource        map[string]string
	Traces          TraceConfig
	Metrics         MetricConfig
	Propagation     telemetrypropagation.Config
	RegisterGlobal  bool
	ShutdownTimeout time.Duration
}

Config describes the complete runtime. Constructing it has no side effects.

func DefaultConfig

func DefaultConfig(serviceName, serviceVersion string) Config

DefaultConfig returns inspectable defaults suitable for exporting to a Collector sidecar or cluster-local agent.

func (Config) Validate

func (c Config) Validate() error

Validate reports every invalid setting in the configuration.

type ExporterConfig

type ExporterConfig struct {
	Protocol    Protocol
	Endpoint    string
	URLPath     string
	Headers     map[string]string
	Compression Compression
	TLS         TLSConfig
	Retry       RetryConfig
	Timeout     time.Duration
}

ExporterConfig controls an OTLP exporter.

type MetricConfig

type MetricConfig struct {
	Enabled          bool
	Exporter         ExporterConfig
	ExportInterval   time.Duration
	ExportTimeout    time.Duration
	CardinalityLimit int
	Views            []telemetrymetric.ViewConfig
}

MetricConfig controls the metric provider and exporter.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option customizes runtime construction. Options are primarily useful for deterministic testing and custom Collector transports.

func WithMetricExporter

func WithMetricExporter(exporter metricexport.Exporter) Option

WithMetricExporter supplies a standard OpenTelemetry metric exporter.

func WithTraceExporter

func WithTraceExporter(exporter trace.SpanExporter) Option

WithTraceExporter supplies a standard OpenTelemetry span exporter.

type Protocol

type Protocol string

Protocol selects an OTLP transport.

const (
	// ProtocolGRPC exports OTLP using gRPC.
	ProtocolGRPC Protocol = "grpc"
	// ProtocolHTTPProtobuf exports OTLP using HTTP and protobuf.
	ProtocolHTTPProtobuf Protocol = "http/protobuf"
)

type RetryConfig

type RetryConfig struct {
	Enabled         bool
	InitialInterval time.Duration
	MaxInterval     time.Duration
	MaxElapsedTime  time.Duration
}

RetryConfig bounds exporter retry behavior.

type Runtime

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

Runtime owns the providers and their complete lifecycle.

func Init

func Init(ctx context.Context, config Config, opts ...Option) (*Runtime, error)

Init validates config and explicitly initializes the telemetry runtime.

func (*Runtime) ForceFlush

func (r *Runtime) ForceFlush(ctx context.Context) error

ForceFlush exports all telemetry queued by the runtime.

func (*Runtime) Meter

func (r *Runtime) Meter(name string, options ...metric.MeterOption) metric.Meter

Meter returns a standard OpenTelemetry meter.

func (*Runtime) MeterProvider

func (r *Runtime) MeterProvider() metric.MeterProvider

MeterProvider returns the standard OpenTelemetry meter provider API.

func (*Runtime) Propagator

func (r *Runtime) Propagator() otelpropagation.TextMapPropagator

Propagator returns the runtime's standard OpenTelemetry propagator.

func (*Runtime) Shutdown

func (r *Runtime) Shutdown(ctx context.Context) error

Shutdown unregisters globals owned by this runtime, flushes providers, and shuts them down. Every call returns the same aggregate result.

func (*Runtime) Tracer

func (r *Runtime) Tracer(name string, options ...traceapi.TracerOption) traceapi.Tracer

Tracer returns a standard OpenTelemetry tracer.

func (*Runtime) TracerProvider

func (r *Runtime) TracerProvider() traceapi.TracerProvider

TracerProvider returns the standard OpenTelemetry tracer provider API.

type SamplerConfig

type SamplerConfig struct {
	Mode        telemetrytrace.Mode
	Ratio       float64
	ParentBased bool
}

SamplerConfig controls parent-based ratio sampling.

type ServiceConfig

type ServiceConfig struct {
	Name      string
	Version   string
	Namespace string
	Instance  string
}

ServiceConfig identifies the process producing telemetry.

type TLSConfig

type TLSConfig struct {
	Insecure           bool
	CAFile             string
	CertificateFile    string
	PrivateKeyFile     string
	ServerName         string
	InsecureSkipVerify bool
}

TLSConfig controls transport security. Insecure is intended for a local or same-cluster Collector connection and must be selected explicitly.

type TraceConfig

type TraceConfig struct {
	Enabled  bool
	Exporter ExporterConfig
	Batch    BatchConfig
	Sampler  SamplerConfig
}

TraceConfig controls the trace provider and exporter.

Directories

Path Synopsis
examples
internal/exampleconfig
Package exampleconfig maps standard OpenTelemetry environment variables to the explicit telemetry configuration used by the examples.
Package exampleconfig maps standard OpenTelemetry environment variables to the explicit telemetry configuration used by the examples.
service command
Command service demonstrates HTTP service lifecycle and instrumentation.
Command service demonstrates HTTP service lifecycle and instrumentation.
worker command
Command worker demonstrates a bounded worker telemetry lifecycle.
Command worker demonstrates a bounded worker telemetry lifecycle.
instrumentation
gocache
Package gocache provides dependency-neutral instrumentation for cache.
Package gocache provides dependency-neutral instrumentation for cache.
gohttpclient
Package gohttpclient adapts the privacy-preserving net/http client bridge to http-client's standard RoundTripper composition seam.
Package gohttpclient adapts the privacy-preserving net/http client bridge to http-client's standard RoundTripper composition seam.
gopostgres
Package gopostgres provides a privacy-preserving pgx tracing bridge for postgres.
Package gopostgres provides a privacy-preserving pgx tracing bridge for postgres.
goqueue
Package goqueue provides dependency-neutral handler instrumentation for queue.
Package goqueue provides dependency-neutral handler instrumentation for queue.
goruntime
Package goruntime exports bounded Go runtime metrics without starting a background collector or registering global providers.
Package goruntime exports bounded Go runtime metrics without starting a background collector or registering global providers.
nethttp
Package nethttp instruments net/http servers and clients without recording raw URLs, hosts, headers, bodies, client addresses, or arbitrary methods.
Package nethttp instruments net/http servers and clients without recording raw URLs, hosts, headers, bodies, client addresses, or arbitrary methods.
Package metric defines bounded metric SDK configuration, views, and cardinality controls.
Package metric defines bounded metric SDK configuration, views, and cardinality controls.
Package otlp constructs explicitly configured OTLP trace and metric exporters without reading vendor-specific settings.
Package otlp constructs explicitly configured OTLP trace and metric exporters without reading vendor-specific settings.
Package propagation provides bounded W3C propagation with explicit inbound trust decisions.
Package propagation provides bounded W3C propagation with explicit inbound trust decisions.
Package telemetryservice adapts an explicit telemetry runtime to the service lifecycle.
Package telemetryservice adapts an explicit telemetry runtime to the service lifecycle.
Package testtelemetry provides deterministic in-memory providers for tests.
Package testtelemetry provides deterministic in-memory providers for tests.
Package trace defines stable trace configuration and sampling policies.
Package trace defines stable trace configuration and sampling policies.

Jump to

Keyboard shortcuts

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