# Python Instrument Python applications with OpenTelemetry # Integration Instrument your Python applications to send traces, logs, and metrics to Kopai. ## Installation ```bash pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http ``` ## Basic Setup Initialize OpenTelemetry in your application: ```python 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. ## Running Your Application Set the required environment variables and run: ```bash export OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp-http.kopai.app" export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_TOKEN" export OTEL_SERVICE_NAME="my-service" python app.py ``` | Variable | Description | |----------|-------------| | `OTEL_EXPORTER_OTLP_ENDPOINT` | Kopai OTLP endpoint | | `OTEL_EXPORTER_OTLP_HEADERS` | Auth header with your backend token | | `OTEL_SERVICE_NAME` | Name shown in Kopai UI | ## Auto-Instrumentation For automatic instrumentation, use the distro package: ```bash pip install opentelemetry-distro opentelemetry-bootstrap -a install opentelemetry-instrument python app.py ``` This provides automatic instrumentation for Flask, Django, FastAPI, requests, and more. ## Working Example For a complete working example: **[Python Example](https://github.com/kopai-app/kopai-integration-examples/tree/main/python)**