Python SDK
Python SDK
Section titled “Python SDK”Instrument your Python applications to send traces and logs to Kopai.
Installation
Section titled “Installation”pip install opentelemetry-api opentelemetry-sdk \ opentelemetry-exporter-otlp-proto-http \ opentelemetry-instrumentationBasic Setup
Section titled “Basic Setup”from opentelemetry import tracefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterimport os
# Configure the tracerprovider = TracerProvider()processor = BatchSpanProcessor( OTLPSpanExporter( endpoint="https://otlp.kopai.app/v1/traces", headers={"Authorization": f"Bearer {os.environ['KOPAI_TOKEN']}"}, ))provider.add_span_processor(processor)trace.set_tracer_provider(provider)Running Your Application
Section titled “Running Your Application”export KOPAI_TOKEN="your-token-here"export OTEL_SERVICE_NAME="my-service"python app.pyAuto-Instrumentation
Section titled “Auto-Instrumentation”Install instrumentation packages for your framework:
# Flaskpip install opentelemetry-instrumentation-flask
# Djangopip install opentelemetry-instrumentation-django
# FastAPIpip install opentelemetry-instrumentation-fastapiThen instrument:
from opentelemetry.instrumentation.flask import FlaskInstrumentor
app = Flask(__name__)FlaskInstrumentor().instrument_app(app)Manual Instrumentation
Section titled “Manual Instrumentation”from opentelemetry import trace
tracer = trace.get_tracer("my-service")
def process_order(order_id: str): with tracer.start_as_current_span("processOrder") as span: span.set_attribute("order.id", order_id) # Your logic here return result