Tracing Package

API reference for rivaas.dev/tracing - Distributed tracing for Go applications

This is the API reference for the rivaas.dev/tracing package. For learning-focused documentation, see the Tracing Guide.

Package Information

Package Overview

The tracing package provides OpenTelemetry-based distributed tracing for Go applications with support for multiple exporters including Stdout, OTLP (gRPC and HTTP), and Noop.

Core Features

  • Multiple tracing providers (Stdout, OTLP, Noop)
  • Built-in HTTP middleware for request tracing
  • Manual span management with attributes and events
  • Context propagation for distributed tracing
  • Thread-safe operations
  • Span lifecycle hooks
  • Testing utilities

Architecture

The package is built on OpenTelemetry and provides a simplified interface for distributed tracing.

graph TD
    App[Application Code]
    Tracer[Tracer]
    Provider[Provider Layer]
    Noop[Noop]
    Stdout[Stdout]
    OTLP[OTLP gRPC/HTTP]
    Middleware[HTTP Middleware]
    Context[Context Propagation]
    
    App -->|Create Spans| Tracer
    Middleware -->|Auto-Trace| Tracer
    Tracer --> Provider
    Provider --> Noop
    Provider --> Stdout
    Provider --> OTLP
    Tracer --> Context
    Context -->|Extract/Inject| Middleware

Components

Main Package (rivaas.dev/tracing)

Core tracing functionality including:

  • Tracer - Main tracer for creating and managing spans
  • New() / MustNew() - Tracer initialization
  • Span management - Create, finish, add attributes/events
  • Middleware() - HTTP request tracing
  • ContextTracing - Helper for router context integration
  • Context helpers - Extract, inject, get trace IDs
  • Testing utilities

Quick API Index

Tracer Creation

tracer, err := tracing.New(options...)     // With error handling
tracer := tracing.MustNew(options...)      // Panics on error

Lifecycle Management

err := tracer.Start(ctx context.Context)   // Start OTLP providers
err := tracer.Shutdown(ctx context.Context) // Graceful shutdown

Span Management

// Create spans
ctx, span := tracer.StartSpan(ctx, "operation-name")
tracer.FinishSpan(span, statusCode)

// Add attributes
tracer.SetSpanAttribute(span, "key", value)

// Add events
tracer.AddSpanEvent(span, "event-name", attrs...)

Context Propagation

// Extract from incoming requests
ctx := tracer.ExtractTraceContext(ctx, req.Header)

// Inject into outgoing requests
tracer.InjectTraceContext(ctx, req.Header)

HTTP Middleware

handler := tracing.Middleware(tracer, options...)(httpHandler)
handler := tracing.MustMiddleware(tracer, options...)(httpHandler)

Context Helpers

traceID := tracing.TraceID(ctx)
spanID := tracing.SpanID(ctx)
tracing.SetSpanAttributeFromContext(ctx, "key", value)
tracing.AddSpanEventFromContext(ctx, "event-name", attrs...)

Testing Utilities

tracer := tracing.TestingTracer(t, options...)
tracer := tracing.TestingTracerWithStdout(t, options...)
middleware := tracing.TestingMiddleware(t, middlewareOptions...)

ContextTracing Helper

ct := tracing.NewContextTracing(ctx, tracer, span)
ct.SetSpanAttribute("key", value)
ct.AddSpanEvent("event-name", attrs...)
traceID := ct.TraceID()

Reference Pages

API Reference

Tracer type, span management, and context propagation.

View →

Options

Configuration options for providers and sampling.

View →

Middleware Options

HTTP middleware configuration and path exclusion.

View →

Troubleshooting

Common tracing issues and solutions.

View →

User Guide

Step-by-step tutorials and examples.

View →

Type Reference

Tracer

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

Main tracer for distributed tracing. Thread-safe for concurrent access.

Methods: See API Reference for complete method documentation.

Option

type Option func(*Tracer)

Configuration option function type used with New() and MustNew().

Available Options: See Options for all options.

MiddlewareOption

type MiddlewareOption func(*middlewareConfig)

HTTP middleware configuration option.

Available Options: See Middleware Options for all options.

Provider

type Provider string

const (
    NoopProvider     Provider = "noop"
    StdoutProvider   Provider = "stdout"
    OTLPProvider     Provider = "otlp"
    OTLPHTTPProvider Provider = "otlp-http"
)

Available tracing providers.

EventType

type EventType int

const (
    EventError   EventType = iota // Error events
    EventWarning                   // Warning events
    EventInfo                      // Informational events
    EventDebug                     // Debug events
)

Event severity levels for internal operational events.

Event

type Event struct {
    Type    EventType
    Message string
    Args    []any // slog-style key-value pairs
}

Internal operational event from the tracing package.

EventHandler

type EventHandler func(Event)

Processes internal operational events. Used with WithEventHandler option.

SpanStartHook

type SpanStartHook func(ctx context.Context, span trace.Span, req *http.Request)

Callback invoked when a request span is started.

SpanFinishHook

type SpanFinishHook func(span trace.Span, statusCode int)

Callback invoked when a request span is finished.

Common Patterns

Basic Usage

tracer := tracing.MustNew(
    tracing.WithServiceName("my-api"),
    tracing.WithOTLP("localhost:4317"),
)
tracer.Start(context.Background())
defer tracer.Shutdown(context.Background())

ctx, span := tracer.StartSpan(ctx, "operation")
defer tracer.FinishSpan(span, http.StatusOK)

With HTTP Middleware

tracer := tracing.MustNew(
    tracing.WithServiceName("my-api"),
    tracing.WithOTLP("localhost:4317"),
)
tracer.Start(context.Background())

handler := tracing.MustMiddleware(tracer,
    tracing.WithExcludePaths("/health"),
)(httpHandler)

http.ListenAndServe(":8080", handler)

Distributed Tracing

// Service A - inject trace context
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
tracer.InjectTraceContext(ctx, req.Header)
resp, _ := http.DefaultClient.Do(req)

// Service B - extract trace context
ctx = tracer.ExtractTraceContext(r.Context(), r.Header)
ctx, span := tracer.StartSpan(ctx, "operation")
defer tracer.FinishSpan(span, http.StatusOK)

Thread Safety

The Tracer type is thread-safe for:

  • All span management methods
  • Concurrent Start() and Shutdown() operations
  • Mixed tracing and lifecycle operations
  • Context propagation methods

Not thread-safe for:

  • Concurrent modification during initialization

Performance Notes

  • Request overhead (100% sampling): ~1.6 microseconds
  • Start/Finish span: ~160 nanoseconds
  • Set attribute: ~3 nanoseconds
  • Path exclusion (100 paths): ~9 nanoseconds

Best Practices:

  • Use sampling for high-traffic endpoints
  • Exclude health checks and metrics endpoints
  • Limit span attribute cardinality
  • Use path prefixes instead of regex when possible

Comparison with Metrics Package

The tracing package follows the same design pattern as the metrics package:

AspectMetrics PackageTracing Package
Main TypeRecorderTracer
Provider OptionsWithPrometheus(), WithOTLP()WithOTLP(), WithStdout(), WithNoop()
ConstructorNew(opts...) (*Recorder, error)New(opts...) (*Tracer, error)
Panic VersionMustNew(opts...) *RecorderMustNew(opts...) *Tracer
MiddlewareMiddleware(recorder, opts...)Middleware(tracer, opts...)
Panic MiddlewareMustMiddleware(recorder, opts...)MustMiddleware(tracer, opts...)
Path ExclusionMiddlewareOptionMiddlewareOption
Header RecordingMiddlewareOptionMiddlewareOption

Version Compatibility

The tracing package follows semantic versioning. The API is stable for the v1 series.

Minimum Go version: 1.25

OpenTelemetry compatibility: Uses OpenTelemetry SDK v1.x

Next Steps

For learning-focused guides, see the Tracing Guide.