OpenTracing Python API

2.4.0 · deprecated · verified Sun Apr 12

OpenTracing is a vendor-neutral API for distributed tracing. This Python library (version 2.4.0) provides the OpenTracing API specification and a basic no-op implementation, requiring a concrete tracer implementation (e.g., Jaeger, Zipkin) for actual tracing data collection. The OpenTracing project has been officially archived by the CNCF, with its functionality superseded by OpenTelemetry. New projects are strongly encouraged to use OpenTelemetry, and existing users should plan for migration.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a MockTracer (for testing), set it as the global tracer, and then create nested spans using `start_active_span` with context managers. In a production environment, `MockTracer` would be replaced by a specific tracer client (e.g., `JaegerTracer`, `ZipkinTracer`) that exports telemetry data to a tracing backend.

import opentracing
from opentracing.mocktracer import MockTracer

# 1. Initialize a Tracer implementation (e.g., MockTracer for testing)
# In a real application, you would use a concrete tracer like JaegerTracer.
tracer = MockTracer()
opentracing.set_global_tracer(tracer)

# 2. Start a root span
with opentracing.global_tracer().start_active_span('root_operation') as scope:
    root_span = scope.span
    root_span.set_tag('component', 'quickstart_example')
    root_span.log_kv({'event': 'started root operation'})

    # 3. Create a child span
    with opentracing.global_tracer().start_active_span('child_operation') as child_scope:
        child_span = child_scope.span
        child_span.set_tag('type', 'internal_call')
        child_span.log_kv({'event': 'executing child logic'})

    root_span.log_kv({'event': 'finished root operation'})

# For MockTracer, retrieve finished spans for assertion
finished_spans = tracer.finished_spans
assert len(finished_spans) == 2
assert finished_spans[0].operation_name == 'child_operation'
assert finished_spans[1].operation_name == 'root_operation'

print(f"Captured {len(finished_spans)} spans:")
for span in finished_spans:
    print(f" - {span.operation_name}, Tags: {span.tags}, Logs: {span.logs}")

view raw JSON →