Skip to main content

Overview

The trace middleware propagates distributed tracing context (trace ID, span ID) across service boundaries for observability. Use it when you need:
  • Distributed tracing
  • Request correlation
  • Service observability

Installation

Quick Start

Configuration

Options

Examples

Basic Tracing

W3C Trace Context

Custom Headers

Access Trace Info

Propagate to Downstream

API Reference

Functions

Technical Details

Implementation Architecture

The trace middleware implements distributed tracing through:
  1. Context Propagation: Uses Go’s context.Context to store span information throughout the request lifecycle
  2. Span Generation: Creates unique trace and span IDs using cryptographic randomness (16 bytes encoded as hex)
  3. Header-based Propagation: Extracts and injects trace context via HTTP headers for cross-service communication

Core Components

Span Structure
  • TraceID: Unique identifier for the entire trace across services
  • SpanID: Unique identifier for this specific operation
  • ParentID: Reference to the parent span for hierarchy
  • StartTime/EndTime: Timing information for duration calculation
  • Status: Enumerated status (Unset, OK, Error)
  • Tags: Key-value metadata for context
  • Events: Timestamped events within the span
ID Generation Uses crypto/rand to generate 16-byte random values, encoded as 32-character hexadecimal strings, ensuring globally unique identifiers with negligible collision probability. Span Lifecycle
  1. Extract or generate trace ID from request headers
  2. Create new span with generated span ID
  3. Store span in request context
  4. Set response headers for downstream propagation
  5. Execute handler chain
  6. Calculate duration and set final status
  7. Invoke OnSpan callback if configured
Collector Pattern The Collector provides a simple way to aggregate spans for testing or custom backends:
  • Thread-safe span collection
  • In-memory storage
  • Clear method for test isolation

Configuration Defaults

Best Practices

  • Use consistent format across services
  • Include trace ID in all logs
  • Propagate to all downstream calls
  • Consider W3C standard for interoperability

Testing

The trace middleware includes comprehensive test coverage for all features: