BasicTracer Python

3.2.0 · active · verified Thu Apr 16

basictracer is a Python implementation of the OpenTracing API, providing a simple, in-memory tracer suitable for development and testing. It allows applications to instrument code with spans, logs, and baggage, adhering to the OpenTracing specification. The current version is 3.2.0, and its release cadence is infrequent, with the last major update in 2021.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `BasicTracer` with an `InMemoryRecorder`, set it as the global OpenTracing tracer, and create a basic span with logs. It also shows how to retrieve the recorded spans. Remember that `BasicTracer` stores spans in memory and does not export them.

import opentracing
from basictracer import BasicTracer
from basictracer.recorder import InMemoryRecorder

# Initialize an in-memory recorder to store spans
recorder = InMemoryRecorder()
# Create a BasicTracer instance
tracer = BasicTracer(recorder=recorder)

# It's common practice to set the global tracer
opentracing.set_global_tracer(tracer)

# Start a new span using the global tracer
with opentracing.start_active_span('my_operation') as scope:
    span = scope.span
    span.log_kv({'event': 'start_work', 'stage': 1})

    # Simulate some work
    result = "some data"

    span.log_kv({'event': 'finish_work', 'result_len': len(result)})

# Retrieve recorded spans
print(f"Recorded {len(recorder.spans)} span(s).")
for s in recorder.spans:
    print(f"  Operation: {s.operation_name}, Duration: {s.duration}ns")
    print(f"  Logs: {s.logs}")

# Example of Child-Of span
with opentracing.start_active_span('parent_span') as parent_scope:
    with opentracing.start_active_span('child_span', child_of=parent_scope.span):
        pass # Child-Of span created

print(f"Total recorded spans after second block: {len(recorder.spans)}")

view raw JSON →