OpenTelemetry Instrumentation for Django

0.61b0 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

This quickstart demonstrates how to manually initialize OpenTelemetry and instrument a Django application. The `DjangoInstrumentor().instrument()` call sets up automatic tracing for HTTP requests, database queries, and other Django components. For a zero-code setup, `opentelemetry-instrument` wrapper is commonly used (e.g., `opentelemetry-instrument python manage.py runserver`).

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`

view raw JSON →