OpenCensus Python

0.11.4 · maintenance · verified Sun Mar 29

OpenCensus Python is a framework for collecting application metrics and distributed traces. It enables developers to gain observability into their systems by providing libraries to gather telemetry data and export it to a chosen backend. The current version is 0.11.4. While the `opencensus-python` repository continues to see updates, the broader OpenCensus project has merged into OpenTelemetry, with users generally encouraged to migrate.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a basic tracer using the `PrintExporter` to output trace data to the console and create nested spans for tracing code execution.

from opencensus.trace.tracer import Tracer
from opencensus.trace.samplers import AlwaysOnSampler
from opencensus.trace.exporters import PrintExporter

def my_function_to_trace():
    print("Doing some work inside the traced function...")

# Initialize a tracer with an exporter and a sampler
exporter = PrintExporter()
tracer = Tracer(exporter=exporter, sampler=AlwaysOnSampler())

# Use the tracer to create a span
with tracer.span(name='my_parent_span') as span:
    span.add_annotation('Starting my_parent_span operation')
    print(f"Current Span ID: {span.span_id}")

    with tracer.span(name='my_child_span') as child_span:
        child_span.add_annotation('Starting my_child_span operation')
        my_function_to_trace()
        child_span.add_annotation('Finished my_child_span operation')

    span.add_annotation('Finished my_parent_span operation')
print("Traced operations complete.")

view raw JSON →