OpenTelemetry Django Instrumentation
Instrument django to trace Django applications.
Usage
from opentelemetry.instrumentation.django import DjangoInstrumentor
DjangoInstrumentor().instrument()
Configuration
Exclude lists
To exclude certain URLs from tracking, set the environment variable OTEL_PYTHON_DJANGO_EXCLUDED_URLS
(or OTEL_PYTHON_EXCLUDED_URLS to cover all instrumentations) to a string of comma delimited regexes that match the
URLs.
For example,
export OTEL_PYTHON_DJANGO_EXCLUDED_URLS="client/.*/info,healthcheck"
will exclude requests such as https://site/client/123/info and https://site/xyz/healthcheck.
Request attributes
To extract attributes from Django’s request object and use them as span attributes, set the environment variable
OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS to a comma delimited list of request attribute names.
For example,
export OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS='path_info,content_type'
will extract the path_info and content_type attributes from every traced request and add them as span attributes.
Request and Response hooks
This instrumentation supports request and response hooks. These are functions that get called right after a span is created for a request and right before the span is finished for the response. The hooks can be configured as follows:
from opentelemetry.instrumentation.django import DjangoInstrumentor
def request_hook(span, request):
pass
def response_hook(span, request, response):
pass
DjangoInstrumentor().instrument(request_hook=request_hook, response_hook=response_hook)
Adding attributes from middleware context
In many Django applications, certain request attributes become available only after specific middlewares have executed. For example:
django.contrib.auth.middleware.AuthenticationMiddlewarepopulatesrequest.userdjango.contrib.sites.middleware.CurrentSiteMiddlewarepopulatesrequest.site
Because the OpenTelemetry instrumentation creates the span before Django middlewares run,
these attributes are not yet available in the request_hook stage.
Therefore, such attributes should be safely attached in the response_hook, which executes after Django finishes processing the request (and after all middlewares have completed).
Example: Attaching the authenticated user and current site to the span:
def response_hook(span, request, response):
# Attach user information if available
if request.user.is_authenticated:
span.set_attribute("enduser.id", request.user.pk)
span.set_attribute("enduser.username", request.user.get_username())
# Attach current site (if provided by CurrentSiteMiddleware)
if hasattr(request, "site"):
span.set_attribute("site.id", getattr(request.site, "pk", None))
span.set_attribute("site.domain", getattr(request.site, "domain", None))
DjangoInstrumentor().instrument(response_hook=response_hook)
This ensures that middleware-dependent context (like user or site information) is properly recorded once Django’s middleware stack has finished execution.
Custom Django middleware can also attach arbitrary data to the request object,
which can later be included as span attributes in the response_hook.
Best practices
Use response_hook (not request_hook) when accessing attributes added by Django middlewares.
Common middleware-provided attributes include:
request.user(AuthenticationMiddleware)request.site(CurrentSiteMiddleware)
Avoid adding large or sensitive data (e.g., passwords, session tokens, PII) to spans.
Use namespaced attribute keys, e.g.,
enduser.*,site.*, orcustom.*, for clarity.Hooks should execute quickly — avoid blocking or long-running operations.
Hooks can be safely combined with OpenTelemetry Context propagation or Baggage for consistent tracing across services.
Middleware execution order
In Django’s request lifecycle, the OpenTelemetry request_hook is executed before the first middleware runs. Therefore:
At request_hook time → only the bare HttpRequest object is available.
After middlewares → request.user, request.site etc. become available.
At response_hook time → all middlewares (including authentication and site middlewares) have already run, making it the correct place to attach these attributes.
Developers who need to trace attributes from middlewares should always use response_hook to ensure complete and accurate span data.
Capture HTTP request and response headers
You can configure the agent to capture specified HTTP headers as span attributes, according to the semantic conventions.
Request headers
To capture HTTP request headers as span attributes, set the environment variable
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST to a comma delimited list of HTTP header names.
For example,
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header"
will extract content-type and custom_request_header from the request headers and add them as span attributes.
Request header names in Django are case-insensitive. So, giving the header name as CUStom-Header in the environment
variable will capture the header named custom-header.
Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*"
Would match all request headers that start with Accept and X-.
To capture all request headers, set OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST to ".*".
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*"
The name of the added span attribute will follow the format http.request.header.<header_name> where <header_name>
is the normalized HTTP header name (lowercase, with - replaced by _). The value of the attribute will be a
single item list containing all the header values.
For example:
http.request.header.custom_request_header = ["<value1>,<value2>"]
Response headers
To capture HTTP response headers as span attributes, set the environment variable
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE to a comma delimited list of HTTP header names.
For example,
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header"
will extract content-type and custom_response_header from the response headers and add them as span attributes.
Response header names in Django are case-insensitive. So, giving the header name as CUStom-Header in the environment
variable will capture the header named custom-header.
Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*"
Would match all response headers that start with Content and X-.
To capture all response headers, set OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE to ".*".
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*"
The name of the added span attribute will follow the format http.response.header.<header_name> where <header_name>
is the normalized HTTP header name (lowercase, with - replaced by _). The value of the attribute will be a
single item list containing all the header values.
For example:
http.response.header.custom_response_header = ["<value1>,<value2>"]
Sanitizing headers
In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords,
etc, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS
to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be
matched in a case-insensitive manner.
For example,
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie"
will replace the value of headers such as session-id and set-cookie with [REDACTED] in the span.
Note
The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change.
SQLCommenter
You can optionally enable sqlcommenter which enriches the query with contextual
information. Queries made after setting up trace integration with sqlcommenter
enabled will have configurable key-value pairs appended to them, e.g.
Users().objects.all() will result in
"select * from auth_users; /*traceparent=00-01234567-abcd-01*/". This
supports context propagation between database client and server when database log
records are enabled. For more information, see:
from opentelemetry.instrumentation.django import DjangoInstrumentor
DjangoInstrumentor().instrument(is_sql_commentor_enabled=True)
Warning
Duplicate sqlcomments may be appended to the sqlquery log if DjangoInstrumentor sqlcommenter is enabled in addition to sqlcommenter for an active instrumentation of a database driver or object-relational mapper (ORM) in the same database client stack. For example, if psycopg2 driver is used and Psycopg2Instrumentor has sqlcommenter enabled, then both DjangoInstrumentor and Psycopg2Instrumentor will append comments to the query statement.
SQLCommenter with commenter_options
The key-value pairs appended to the query can be configured using
variables in Django settings.py. When sqlcommenter is enabled, all
available KVs/tags are calculated by default, i.e. True for each. The
settings.py values support opting out of specific KVs.
Available settings.py commenter options
We can configure the tags to be appended to the sqlquery log by adding below variables to
settings.py, e.g. SQLCOMMENTER_WITH_FRAMEWORK = False
|
Description |
Example |
|---|---|---|
|
Django framework name with version (URL encoded). |
|
|
Django controller/view name that handles the request. |
|
|
URL path pattern that handles the request. |
|
|
Django app name that handles the request. |
|
|
OpenTelemetry context as traceparent at time of query. |
|
|
Database driver name used by Django. |
|
API
- class opentelemetry.instrumentation.django.DjangoInstrumentor(*args, **kwargs)[source]
Bases:
BaseInstrumentorAn instrumentor for Django
See BaseInstrumentor
- instrumentation_dependencies()[source]
Return a list of python packages with versions that the will be instrumented.
The format should be the same as used in requirements.txt or pyproject.toml.
For example, if an instrumentation instruments requests 1.x, this method should look like: :rtype:
Collection[str]- def instrumentation_dependencies(self) -> Collection[str]:
return [‘requests ~= 1.0’]
This will ensure that the instrumentation will only be used when the specified library is present in the environment.