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")
python

Create spans in your application logic:

with tracer.start_as_current_span("my-operation") as span:
    span.set_attribute("key", "value")
    # your work here
python

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.

trace.get_tracer() Returns a No-Op Tracer

If trace.set_tracer_provider() is never called, trace.get_tracer() returns a no-op tracer that silently drops all spans. Ensure the provider is set before calling get_tracer().

Spans Not Exported on Application Exit

BatchSpanProcessor exports spans asynchronously and may not flush before the process exits. Call provider.shutdown() at application exit to force a final flush:

import atexit
atexit.register(provider.shutdown)
python