Pyroscope OpenTelemetry Python Integration

1.0.0 · active · verified Tue Apr 14

The `pyroscope-otel` library for Python provides functionalities to link OpenTelemetry tracing data with Grafana Pyroscope's continuous profiling data. It offers a `SpanProcessor` implementation that automatically attaches profiling identifiers to trace spans, enabling users to correlate traces with detailed performance profiles. The library is actively maintained by Grafana, with its current version being 1.0.0. Releases appear to be somewhat regular, reflecting ongoing development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the essential steps to integrate `pyroscope-otel`. It configures the core Pyroscope profiler, sets up an OpenTelemetry `TracerProvider`, and then registers the `PyroscopeSpanProcessor` to automatically link trace spans with profiling data. Ensure a Pyroscope server is running and accessible at the configured `server_address` (default `http://localhost:4040`).

import os
import time

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor

from pyroscope import configure as pyroscope_configure
from pyroscope.otel import PyroscopeSpanProcessor

# 1. Configure Pyroscope profiler first
pyroscope_configure(
    app_name="my-python-app",
    server_address=os.environ.get("PYROSCOPE_SERVER_ADDRESS", "http://localhost:4040"),
    auth_token=os.environ.get("PYROSCOPE_AUTH_TOKEN", ""), # Optional for Grafana Cloud
    sample_rate=100, # Default sample rate
)

# 2. Configure OpenTelemetry TracerProvider
provider = TracerProvider()

# Add PyroscopeSpanProcessor to link traces and profiles
provider.add_span_processor(PyroscopeSpanProcessor())

# Optional: Add a console exporter for visibility of spans
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))

trace.set_tracer_provider(provider)

# 3. Get a tracer and create spans
tracer = trace.get_tracer(__name__)

def my_function():
    with tracer.start_as_current_span("my-function-span") as span:
        print("Executing my_function...")
        time.sleep(0.05)
        with tracer.start_as_current_span("inner-operation"):
            print("Executing inner_operation...")
            time.sleep(0.02)
        print("my_function finished.")

if __name__ == "__main__":
    print("Starting application with Pyroscope-OpenTelemetry integration...")
    my_function()
    print("Application finished.")
    # Give some time for exporters to send data
    time.sleep(1)

view raw JSON →