Skip to content

OpenTelemetry guide

OpenTelemetry for Django

Django apps slow down in the ORM more often than anywhere else. OpenTelemetry shows every view with its queries, so N+1 patterns are visible in one trace.

3 min read11 sectionsUpdated

On this page

Key points

  • The Django instrumentation traces every request by route, not by raw URL.
  • Database driver instrumentation (psycopg) shows each query as a span.
  • gunicorn workers need care so the exporter runs after the fork.
  • Celery tasks join the trace of the request that queued them.

Install

bash
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install     # picks up django, psycopg/psycopg2, redis, requests, celery ...

Run under gunicorn

bash
export DJANGO_SETTINGS_MODULE=shop.settings
export OTEL_SERVICE_NAME=shop-web
export OTEL_RESOURCE_ATTRIBUTES=service.version=$(git rev-parse --short HEAD),deployment.environment.name=production
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_LOGS_EXPORTER=none

opentelemetry-instrument gunicorn shop.wsgi:application --workers 4 --bind 0.0.0.0:8000

If traces appear from only one worker, or not at all, set up the SDK in gunicorn's post_fork hook instead of before the fork:

gunicorn.conf.pypython
# gunicorn.conf.py
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.instrumentation.django import DjangoInstrumentor
from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor

def post_fork(server, worker):
    provider = TracerProvider(resource=Resource.create({"service.name": "shop-web"}))
    provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))   # reads OTEL_EXPORTER_OTLP_* variables
    trace.set_tracer_provider(provider)
    DjangoInstrumentor().instrument()
    Psycopg2Instrumentor().instrument()

Spotting ORM N+1 queries

Open a slow view's trace. Dozens of near-identical SELECT spans under one request mean a related object is loaded per row. Fix it with select_related (foreign keys) or prefetch_related (many-to-many and reverse relations), then compare the view's p95 and its query count. See how to find slow database queries.

Celery

With opentelemetry-instrumentation-celery installed, start workers the same way (opentelemetry-instrument celery -A shop worker). The task span becomes a child of the request that called .delay(), so a slow checkout that queues an email shows both in one trace.

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

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: shop-web 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.

Frequently asked questions

Does the instrumentation capture SQL parameters?

Statements are recorded with placeholders, not values. VitalRix also strips SQL values before storing anything.

Will it trace Django admin and static files?

It traces any request Django handles. Exclude noisy paths with OTEL_PYTHON_DJANGO_EXCLUDED_URLS, for example health checks.

Check it now, free

  • OpenTelemetry for Flask: Instrument a Flask app with OpenTelemetry, in code or with zero code: trace routes, SQLAlchemy and outgoing calls, and export to VitalRix.
  • OpenTelemetry for FastAPI: Trace a FastAPI service with OpenTelemetry: instrument the app, async database drivers and httpx, run uvicorn workers correctly and export.
  • 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.

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.