OpenTelemetry Python distribution for Uptrace

1.41.0 · active · verified Fri Apr 17

Uptrace provides an OpenTelemetry Python distribution that simplifies the setup of tracing and metrics for Python applications. It pre-configures the OpenTelemetry SDK to send data to the Uptrace backend, making it easier to instrument your code and gain visibility into your application's performance. The current version is 1.41.0, and it follows a regular release cadence, often aligning with OpenTelemetry SDK updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the Uptrace OpenTelemetry distribution, obtain a tracer, and create a simple hierarchy of spans. It correctly handles the Uptrace DSN via an environment variable or a dummy value for demonstration, and includes the essential `shutdown()` call for short-lived applications to ensure traces are exported.

import os
from uptrace import configure_opentelemetry
from opentelemetry import trace

# Retrieve Uptrace DSN from environment variable, or use a dummy for demonstration.
# Replace with your actual Uptrace DSN (e.g., from your Uptrace project settings).
# Example DSN format: "http://<token>@<host>:14101/<project_id>"
dsn = os.environ.get("UPTRACE_DSN")

if not dsn:
    print("WARNING: UPTRACE_DSN environment variable is not set.")
    print("Using a dummy DSN for demonstration purposes. No traces will be sent to Uptrace.")
    # This dummy DSN will not send data to Uptrace.
    # In a real application, you should always provide a valid DSN.
    dsn = "http://user:pass@127.0.0.1:14101/0"

# Configure OpenTelemetry with Uptrace
# The service_name is crucial for identifying your application in Uptrace.
configure_opentelemetry(
    dsn=dsn,
    service_name="my-python-app"
)

# Get a tracer instance
tracer = trace.get_tracer(__name__)

# Create and activate a root span
print("Starting a traced operation...")
with tracer.start_as_current_span("my-root-operation"): # Create a root span
    print("Inside 'my-root-operation'")
    # Simulate some work by creating a nested span
    with tracer.start_as_current_span("my-sub-operation"): # Create a child span
        print("Inside 'my-sub-operation': doing some work...")

print("Operation complete. Attempting to send traces to Uptrace (if DSN is valid).")

# It's crucial to shut down the tracer provider to ensure all buffered spans
# are flushed and exported to Uptrace before the application exits.
# In long-running applications or web frameworks, this is often handled
# automatically by framework integrations or application shutdown hooks.
trace.get_tracer_provider().shutdown()
print("Tracer provider shut down.")

view raw JSON →