Skip to content

OpenTelemetry guide

OpenTelemetry for Python: setup guide

Python has excellent zero-code instrumentation: install a few packages, start your app through opentelemetry-instrument, and HTTP, database and client calls are traced.

4 min read12 sectionsUpdated

On this page

Key points

  • opentelemetry-bootstrap installs instrumentations for the libraries you already use.
  • opentelemetry-instrument wraps your start command; no code changes needed to begin.
  • Configure with environment variables: service name, endpoint, protocol, sampler.
  • Export straight to VitalRix over OTLP/HTTP, or through a Collector.

Install

bash
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install     # adds instrumentation for installed libraries (requests, psycopg, redis, ...)

Run with auto-instrumentation

bash
export OTEL_SERVICE_NAME=billing-api
export OTEL_RESOURCE_ATTRIBUTES=service.version=1.4.2,deployment.environment.name=production
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=none
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318     # the Collector

opentelemetry-instrument python app.py

Add your own spans

billing.pypython
from opentelemetry import trace

tracer = trace.get_tracer("billing")

def create_invoice(order):
    with tracer.start_as_current_span("create invoice") as span:
        span.set_attribute("invoice.lines", len(order.lines))
        total = price(order)          # child spans from instrumented libraries nest here
        span.set_attribute("invoice.currency", order.currency)
        return render_pdf(order, total)

Put the trace ID in your logs

With the logging instrumentation enabled, the standard logging module gains otelTraceID and otelSpanID fields you can add to your format:

bash
export OTEL_PYTHON_LOG_CORRELATION=true
export OTEL_PYTHON_LOG_FORMAT="%(asctime)s %(levelname)s [trace_id=%(otelTraceID)s span_id=%(otelSpanID)s] %(name)s: %(message)s"

Send it to VitalRix

Shortcut. The VitalRix package does all of the above for you: pip install vitalrix, then vitalrix.init() before the app serves: it turns on every installed instrumentation and sends traces, metrics and logging records. It reads VITALRIX_URL, VITALRIX_API_KEY, OTEL_SERVICE_NAME and DEPLOYMENT_ENVIRONMENT.

Directly. VitalRix accepts OTLP over HTTP with protobuf or JSON, which is what the Python exporter sends. Instead of a Collector at localhost:4318, point the exporter at VitalRix with the per-signal endpoints and your API key. Create the key in VitalRix under Settings, API keys, with trace, metric and log ingestion.

bash
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.vitalrix.com/api/v1/traces/otlp/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.vitalrix.com/api/v1/metrics/otlp/v1/metrics
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.vitalrix.com/api/v1/logs/otlp/v1/logs
export OTEL_EXPORTER_OTLP_HEADERS=x-api-key=your_api_key

Through a Collector. Run an OpenTelemetry Collector next to your app, or as a shared service, when the SDK exports over gRPC or you want one place for batching, sampling and retries. It receives from the SDK and forwards to VitalRix with your key.

otel-collector.yamlyaml
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  memory_limiter: { check_interval: 1s, limit_mib: 512 }
  batch: {}
exporters:
  otlphttp/vitalrix:
    traces_endpoint: ${env:VITALRIX_API}/api/v1/traces/otlp/v1/traces
    metrics_endpoint: ${env:VITALRIX_API}/api/v1/metrics/otlp/v1/metrics
    headers:
      x-api-key: ${env:VITALRIX_KEY}
service:
  pipelines:
    traces:  { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
    metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
bash
docker run -d --name otel-collector -p 4317:4317 -p 4318:4318 \
  -e VITALRIX_API=https://api.vitalrix.com -e VITALRIX_KEY=your_api_key \
  -v "$PWD/otel-collector.yaml:/etc/otelcol-contrib/config.yaml" \
  otel/opentelemetry-collector-contrib:latest

Pre-fork servers and workers

Servers that fork workers (gunicorn, uWSGI) can break the background export thread if the SDK starts before the fork. If spans go missing with several workers, initialize the SDK in each worker, for example in gunicorn's post_fork hook, and avoid --preload with auto-instrumentation. Celery workers are instrumented by opentelemetry-instrumentation-celery, which also links tasks to the request that queued them. Framework-specific notes: Django, Flask, FastAPI.

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: billing-api appears in the service catalog within a minute, with request rate, error rate and p95.
  3. Open an endpoint and then one request to see its trace waterfall, including database spans.
  4. If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a check command that sends one test log.

Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.

Verify the setup and avoid the common mistakes

bash
export OTEL_SERVICE_NAME=checkout-api
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production,service.version=2.4.0
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.example.com
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.2
opentelemetry-instrument gunicorn app:app
MistakeEffectFix
No service.nameTraces show up as unknown_serviceSet OTEL_SERVICE_NAME
Gunicorn preload with SDK started in the masterWorkers export nothingInitialise in each worker (post_fork hook) or avoid preload
Library installed after bootstrapIts calls are not tracedRe-run opentelemetry-bootstrap -a install
Sampling at 100% in productionHigh volume and costUse a ratio with parentbased_ so whole traces are kept together

Frequently asked questions

Do I need to change my code?

Not to start. Auto-instrumentation covers web frameworks, database drivers and HTTP clients. Add manual spans later around business logic.

Which Python versions are supported?

Recent OpenTelemetry Python releases support the currently maintained CPython versions. Check the project’s release notes for the exact range.

Can Python export directly to VitalRix?

Yes. VitalRix accepts the protobuf the Python OTLP exporter sends, so set the per-signal endpoints and the x-api-key header, or use the vitalrix package. A Collector is optional.

  • OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
  • OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
  • OpenTelemetry for NestJS: Trace a NestJS service with OpenTelemetry: load the SDK before Nest boots, instrument HTTP, Express and NestJS core, and export JSON to VitalRix.
  • OpenTelemetry for Next.js: Trace a Next.js app with OpenTelemetry using instrumentation.ts: Node.js runtime setup, JSON export straight to VitalRix, fetch spans and Edge caveats.
  • OpenTelemetry for Ruby on Rails: Trace a Ruby on Rails app with OpenTelemetry: gems, an initializer with use_all, ActiveRecord and Sidekiq spans, Puma workers and exporting to VitalRix.
  • OpenTelemetry for .NET and ASP.NET Core: Add OpenTelemetry to an ASP.NET Core app: NuGet packages, AddOpenTelemetry for tracing and metrics, HttpClient spans and custom ActivitySource spans.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.