Skip to content

Python

Instrument your Python applications to send traces, logs, and metrics to Kopai.

Terminal window
pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http

Initialize OpenTelemetry in your application:

from opentelemetry import trace, metrics
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
# Create resource
resource = Resource.create({"service.name": "my-service"})
# Setup traces
trace_provider = TracerProvider(resource=resource)
trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(trace_provider)
# Setup metrics
metric_reader = PeriodicExportingMetricReader(OTLPMetricExporter())
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
metrics.set_meter_provider(meter_provider)

The SDK reads the OTLP endpoint from standard OpenTelemetry environment variables.

Set the required environment variables and run:

Terminal window
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp.kopai.app"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_TOKEN"
export OTEL_SERVICE_NAME="my-service"
python app.py
VariableDescription
OTEL_EXPORTER_OTLP_ENDPOINTKopai OTLP endpoint
OTEL_EXPORTER_OTLP_HEADERSAuth header with your backend token
OTEL_SERVICE_NAMEName shown in Kopai UI

For automatic instrumentation, use the distro package:

Terminal window
pip install opentelemetry-distro
opentelemetry-bootstrap -a install
opentelemetry-instrument python app.py

This provides automatic instrumentation for Flask, Django, FastAPI, requests, and more.

For a complete working example:

Python Example