OpenTelemetry Instrumentation for Django
OpenTelemetry Instrumentation for Django provides automatic and manual instrumentation capabilities for Django web applications. It captures distributed traces, metrics, and logs related to HTTP requests, database queries, template rendering, and cache operations, enabling comprehensive observability and performance monitoring. Maintained as part of the `opentelemetry-python-contrib` project, it receives frequent updates and is currently at version 0.61b0.
Warnings
- breaking As of version 0.61b0, support for Django versions older than 2.0 has been dropped. Applications using older Django versions will need to upgrade Django or pin to an older `opentelemetry-instrumentation-django` version.
- gotcha The library is in a beta (`b0`) release stage, indicating potential API changes or instability. While widely used, be aware of this when deploying to production and monitor for updates.
- gotcha When using `request_hook` to add attributes to spans, attributes dependent on Django's middleware (e.g., `request.user`, `request.site`) will not be available. These should be attached in the `response_hook` instead, which executes after all middlewares have run.
- gotcha For comprehensive automatic instrumentation (e.g., database drivers like psycopg2, redis, requests), the `opentelemetry-bootstrap -a install` command should be run in your environment. This command scans installed packages and installs appropriate instrumentation libraries.
Install
-
pip install opentelemetry-instrumentation-django opentelemetry-distro opentelemetry-exporter-otlp
Imports
- DjangoInstrumentor
from opentelemetry.instrumentation.django import DjangoInstrumentor
Quickstart
import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.instrumentation.django import DjangoInstrumentor
# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": os.environ.get('OTEL_SERVICE_NAME', 'my-django-app')})
provider = TracerProvider(resource=resource)
# For demonstration, export traces to console
# In a real application, you'd use OTLPSpanExporter or similar
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
# Instrument Django
DjangoInstrumentor().instrument()
print("OpenTelemetry Django instrumentation initialized.")
# This code snippet would typically be placed in a Django app's __init__.py
# or a settings-loaded module, ensuring it runs during application startup.
# For a zero-code approach, use `opentelemetry-instrument python manage.py runserver`