Migrate Python OpenTelemetry APM
Overview
The OpenTelemetry Python SDK consists of two PyPI packages: the API and the SDK. It supports manual instrumentation via tracers and spans, function-level instrumentation via decorators, and automatic instrumentation via contrib packages. This page covers installing the SDK, setting up instrumentation, and configuring the OTLP exporter to send traces to Kloudfuse.
Install
Run these commands to install the API, SDK, and OTLP HTTP exporter:
pip install opentelemetry-api
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp-proto-http
Set Up Instrumentation
Initialize the tracer provider at application startup, before any other modules that you want to instrument:
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
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("my-service")
Create spans in your application logic:
with tracer.start_as_current_span("my-operation") as span:
span.set_attribute("key", "value")
# your work here
You can also instrument individual functions using the @tracer.start_as_current_span decorator.
Send to Kloudfuse
Configure the OTLP exporter by setting the following environment variables before starting your application:
export OTEL_EXPORTER_OTLP_ENDPOINT="https://<kloudfuse-hostname>/ingester/otlp" (1)
export OTEL_EXPORTER_OTLP_HEADERS="Kf-Api-Key=<api-key>" (2)
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production"
| 1 | Replace <kloudfuse-hostname> with your Kloudfuse cluster hostname. |
| 2 | Replace <api-key> with your Kloudfuse API key. |
Instrumentation Libraries
OpenTelemetry Python provides contrib packages that automatically instrument popular Python libraries and frameworks. Review the available instrumentation libraries and the full list on GitHub.
Troubleshooting
No Traces Appear
Verify that the tracer provider is initialized before any application code that imports instrumented libraries.
If trace.set_tracer_provider() is called after import flask or import requests, those libraries will not be patched.
Move the SDK initialization to the top of your entry point, before other imports.