Skip to main content

⚡ spanwire

Zero-dependency micro-tracing, distributed context propagation & breadcrumb telemetry engine for Python.

PyPI Version Python Versions License: MIT CI Typing: Typed Dependencies: Zero


💡 Why spanwire?

Standard distributed tracing solutions (like OpenTelemetry SDK) pull in dozens of heavy transitive dependencies, incur noticeable startup delays, and add architectural bloat to lightweight microservices, CLI utilities, serverless functions (AWS Lambda, Cloud Run), and async LLM pipelines.

spanwire delivers enterprise-grade distributed telemetry and error context trails with zero external dependencies, utilizing pure Python standard library primitives (contextvars, dataclasses, time, secrets).

  • 100% W3C Trace Context & Baggage Standard: Interoperable with Datadog, Jaeger, Grafana Tempo, AWS X-Ray, and OpenTelemetry collectors.
  • Flawless Context Propagation: Works out of the box across asyncio coroutines, background tasks, and OS threads without context leakage.
  • In-Memory Breadcrumb Trail: Maintains an efficient circular ring-buffer of recent operational milestones, automatically attached when errors or exceptions occur.
  • Multiple Exporters: ANSI-colorized CLI console, NDJSON/JSONLines for log aggregators (Vector, Fluentd, Promtail), or in-memory collectors for unit testing.
  • Deterministic Sampling: Ratio-based trace hashing guarantees synchronized sampling decisions across distributed microservice boundaries.

📐 Architecture & Flow

sequenceDiagram
    autonumber
    participant Client as API Gateway (Service A)
    participant Wire as W3C HTTP Headers
    participant Worker as Downstream Worker (Service B)
    participant Exporter as Telemetry Exporter

    Client->>Client: Start Span ("checkout.process")
    Client->>Client: Record Breadcrumb ("User tier: VIP")
    Client->>Wire: Inject W3C traceparent & baggage headers
    Wire->>Worker: Forward HTTP Request
    Worker->>Worker: Extract W3C Context (inherits trace_id)
    Worker->>Worker: Execute child span ("db.persist_order")
    Worker-->>Exporter: Export child span ([OK] 12.4ms)
    Client-->>Exporter: Export parent span ([OK] 45.1ms)

🚀 Installation

pip install spanwire

Requires Python 3.10 or higher. No third-party dependencies required.


⚡ Quick Start

1. Basic Spans and Console Export

import time
from spanwire import Tracer, ConsoleExporter

tracer = Tracer(
    service_name="payment-service",
    exporter=ConsoleExporter(colored=True)
)

tracer.add_breadcrumb("Validating customer cart", category="cart")

with tracer.span("process_payment", attributes={"order.id": "ord_1042", "amount": 89.00}) as span:
    time.sleep(0.02)
    
    # Nested child span
    with tracer.span("stripe.charge") as child:
        time.sleep(0.03)
        child.set_attribute("charge.id", "ch_abc123")
        tracer.add_breadcrumb("Payment captured via webhook", category="billing")

Console Output:

⚡ [OK] stripe.charge (30.12ms) [trace=63d3791c.. span=ff0dba3fa8e11f3c parent=97bc44600e80142d]
   ↳ attributes: service.name='payment-service', charge.id='ch_abc123'
   ↳ breadcrumbs (2):
     - [INFO] cart: Validating customer cart
     - [INFO] billing: Payment captured via webhook
⚡ [OK] process_payment (50.84ms) [trace=63d3791c.. span=97bc44600e80142d]
   ↳ attributes: service.name='payment-service', order.id='ord_1042', amount=89.0

2. Distributed Tracing over HTTP (W3C Traceparent & Baggage)

import requests
from spanwire import Tracer, set_baggage_item

tracer = Tracer(service_name="gateway")

# Set user context in baggage
set_baggage_item("user_id", "u_8841")

with tracer.span("http_outgoing_call") as span:
    # 1. Inject W3C headers into outbound HTTP request
    headers = {}
    tracer.inject_headers(headers)
    # headers contains:
    # 'traceparent': '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
    # 'baggage': 'user_id=u_8841'

    # requests.get("https://worker.internal/api/tasks", headers=headers)

On the receiving downstream service:

from spanwire import Tracer

worker_tracer = Tracer(service_name="worker")

def handle_incoming_request(incoming_headers: dict):
    # Extract parent context & baggage from headers
    parent_ctx, baggage, _ = worker_tracer.extract_headers(incoming_headers)

    # Continue the distributed trace seamlessly
    with worker_tracer.span("worker.handle_job", parent_context=parent_ctx) as span:
        print(f"Propagated trace_id: {span.context.trace_id}")
        print(f"Parent span_id:      {span.parent_span_id}")
        print(f"User ID from baggage: {baggage.get('user_id')}")

3. Asynchronous Function Decoration & LLM Agent Pipeline

import asyncio
from spanwire import Tracer, ConsoleExporter

tracer = Tracer(service_name="llm-orchestrator", exporter=ConsoleExporter())

@tracer.trace(name="llm.generate_plan")
async def generate_plan(prompt: str) -> list[str]:
    tracer.add_breadcrumb(f"Generating plan for: {prompt[:30]}", category="llm")
    await asyncio.sleep(0.05)
    return ["search_db", "render_markdown"]

async def main():
    with tracer.span("orchestrate_query"):
        plan = await generate_plan("Summarize latest server telemetry")

asyncio.run(main())

🛠️ Exporters

Exporter Description Best Suited For
ConsoleExporter Formatted CLI output with ANSI colors, durations, and breadcrumb trails Development, debugging, CLI tools
JsonLinesExporter Newline-delimited JSON (NDJSON) output to file or stdout Vector, Promtail, Datadog Agent, CloudWatch
InMemoryExporter Stores finished spans in a thread-safe list Pytest unit assertions, custom telemetry queues
CallbackExporter Invokes custom callback function on each completed span Custom event emission, Webhooks

🎯 Samplers

  • AlwaysOnSampler(): Traces 100% of operations (default).
  • AlwaysOffSampler(): Disables tracing overhead completely.
  • RatioSampler(ratio=0.1): Probabilistically samples 10% of traces using deterministic hashing on trace_id.
  • ParentBasedSampler(root=...): Respects the upstream service's sampling flag, with fallback to root sampler.

🧪 Running Unit Tests

python -m pytest tests -v

All 33 unit tests execute in ~0.15s with zero external test plugins.


📜 License

MIT License © 2026 Hamidreza Moghaddam Kohi. See LICENSE for details.

Metadata

Release files for spanwire 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spanwire 0.1.0
File Size Uploaded Provenance Actions
spanwire-0.1.0.tar.gz 22.6 kB With provenance Details for spanwire-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spanwire 0.1.0
File Interpreter ABI Platform Actions
spanwire-0.1.0-py3-none-any.whl Python 3 none any Details for spanwire-0.1.0-py3-none-any.whl

Total release size: 40.0 kB

Release files / spanwire-0.1.0.tar.gz

Download URL spanwire-0.1.0.tar.gz
Size 22.6 kB
Tags Source
SHA-256 checksum
How to use checksums
fd8e8f353cea20b801b12c9d9937e91fd9015158949543b93f727fe37329b4a0
BLAKE2b-256 checksum
How to use checksums
348947a2e72ddcbcc4f2be01ce703ee7e1a8a2f714e13e9bc4165791a09c97cb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / spanwire-0.1.0-py3-none-any.whl

Download URL spanwire-0.1.0-py3-none-any.whl
Size 17.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b2691b1c5e2725bf57068c5b204a6d0398e6f1f9d7c384261911f9c5aa61dfde
BLAKE2b-256 checksum
How to use checksums
471485985f8cf157eafb3c1084938f2c67d880b9e24c575f533b1fb48c43dff1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for spanwire 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for spanwire-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page