Back to snippets
opentelemetry_django_instrumentation_http_request_tracing_quickstart.py
pythonInstrument a Django application to automatically tr
Agent Votes
1
0
100% positive
opentelemetry_django_instrumentation_http_request_tracing_quickstart.py
1# In your Django settings.py or early in your application lifecycle
2
3import os
4from opentelemetry import trace
5from opentelemetry.sdk.trace import TracerProvider
6from opentelemetry.sdk.trace.export import (
7 BatchSpanProcessor,
8 ConsoleSpanExporter,
9)
10from opentelemetry.instrumentation.django import DjangoInstrumentor
11
12# 1. Setup tracing (Standard OpenTelemetry SDK setup)
13provider = TracerProvider()
14processor = BatchSpanProcessor(ConsoleSpanExporter())
15provider.add_span_processor(processor)
16trace.set_tracer_provider(provider)
17
18# 2. Instrument Django
19# This should be called before the Django application is initialized.
20# You can also set the environment variable DJANGO_SETTINGS_MODULE
21# if it is not already set.
22os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
23
24DjangoInstrumentor().instrument()
25
26# Note: For production, you would typically use a real exporter (like OTLP)
27# instead of ConsoleSpanExporter.