This guide demonstrates how to use OpenTelemetry SDK to instrument Python code and send traces to TrueFoundry’s OtelCollector.
In this example, we’ll show how to instrument a simple Python application with nested function calls using OpenTelemetry’s context managers.
Create Tracing Project, API Key and copy tracing code
Follow the instructions in Getting Started to create a tracing project, generate API key and copy the
tracing code.
Install Dependencies
First, you need to install the following packages:
pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http python-dotenv
Add tracing code to Python application
To enable tracing, you’ll need to configure opentelemetry sdk and intialize it.
This section shows how to instrument your Python code using OpenTelemetry’s context managers. The example demonstrates nested function calls with proper tracing.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Setup tracer provider
provider = TracerProvider()
trace.set_tracer_provider(provider)
TFY_API_KEY = os.environ.get("TFY_API_KEY")
# OTLP exporter (HTTP)
otlp_exporter = OTLPSpanExporter(
endpoint="{enter_your_api_endpoint}/v1/traces",
headers={
"Authorization": f"Bearer {TFY_API_KEY}",
"TFY-Tracing-Project": "<enter_your_tracing_project_fqn>",
}
)
# Span processor using batch (recommended for production)
span_processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(span_processor)
# Get tracer
tracer = trace.get_tracer(__name__)
# Child function — will create its own span
def greet_user(name):
with tracer.start_as_current_span("greet_user_task") as span:
# Add attributes to the span
span.set_attribute("user.name", name)
span.set_attribute("greeting.type", "welcome")
print(f"Hello, {name}!")
# Parent function — also creates a span and calls the child
def main():
with tracer.start_as_current_span("main_task"):
user_name = "Sateesh"
greet_user(user_name)
print("Main task finished.")
# Run the main function
main()
Run your application and view logged trace