OpenTelemetry ASGI Instrumentation
This library provides a ASGI middleware that can be used on any ASGI framework (such as Django, Starlette, FastAPI or Quart) to track requests timing through OpenTelemetry.
Installation
pip install opentelemetry-instrumentation-asgi
References
API
The opentelemetry-instrumentation-asgi package provides an ASGI middleware that can be used on any ASGI framework (such as Django-channels / Quart) to track request timing through OpenTelemetry.
Usage (Quart)
from quart import Quart
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
app = Quart(__name__)
app.asgi_app = OpenTelemetryMiddleware(app.asgi_app)
@app.route("/")
async def hello():
return "Hello!"
if __name__ == "__main__":
app.run(debug=True)
Usage (Django 3.0)
Modify the application’s asgi.py
file as shown below.
import os
from django.core.asgi import get_asgi_application
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'asgi_example.settings')
application = get_asgi_application()
application = OpenTelemetryMiddleware(application)
Usage (Raw ASGI)
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
app = ... # An ASGI application.
app = OpenTelemetryMiddleware(app)
Configuration
Request/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 server request hook is passed a server span and ASGI scope object for every incoming request.
The client request hook is called with the internal span and an ASGI scope when the method
receive
is called.The client response hook is called with the internal span and an ASGI event when the method
send
is called.
For example,
def server_request_hook(span: Span, scope: dict[str, Any]):
if span and span.is_recording():
span.set_attribute("custom_user_attribute_from_request_hook", "some-value")
def client_request_hook(span: Span, scope: dict[str, Any], message: dict[str, Any]):
if span and span.is_recording():
span.set_attribute("custom_user_attribute_from_client_request_hook", "some-value")
def client_response_hook(span: Span, scope: dict[str, Any], message: dict[str, Any]):
if span and span.is_recording():
span.set_attribute("custom_user_attribute_from_response_hook", "some-value")
OpenTelemetryMiddleware().(application, server_request_hook=server_request_hook, client_request_hook=client_request_hook, client_response_hook=client_response_hook)
Capture HTTP request and response headers
You can configure the agent to capture specified HTTP headers as span attributes, according to the semantic convention.
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 ASGI 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
list containing 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 ASGI 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
list containing 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.
API
- class opentelemetry.instrumentation.asgi.ASGIGetter[source]
- opentelemetry.instrumentation.asgi.collect_request_attributes(scope, sem_conv_opt_in_mode=_StabilityMode.DEFAULT)[source]
Collects HTTP request attributes from the ASGI scope and returns a dictionary to be used as span creation attributes.
- opentelemetry.instrumentation.asgi.collect_custom_headers_attributes(scope_or_response_message, sanitize, header_regexes, normalize_names)[source]
Returns custom HTTP request or response headers to be added into SERVER span as span attributes.
- opentelemetry.instrumentation.asgi.get_host_port_url_tuple(scope)[source]
Returns (host, port, full_url) tuple.
- opentelemetry.instrumentation.asgi.set_status_code(span, status_code, metric_attributes=None, sem_conv_opt_in_mode=_StabilityMode.DEFAULT)[source]
Adds HTTP response attributes to span using the status_code argument.
- opentelemetry.instrumentation.asgi.get_default_span_details(scope)[source]
Default span name is the HTTP method and URL path, or just the method. https://github.com/open-telemetry/opentelemetry-specification/pull/3165 https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/http/#name
- class opentelemetry.instrumentation.asgi.OpenTelemetryMiddleware(app, excluded_urls=None, default_span_details=None, server_request_hook=None, client_request_hook=None, client_response_hook=None, tracer_provider=None, meter_provider=None, tracer=None, meter=None, http_capture_headers_server_request=None, http_capture_headers_server_response=None, http_capture_headers_sanitize_fields=None, exclude_spans=None)[source]
Bases:
object
The ASGI application middleware.
This class is an ASGI middleware that starts and annotates spans for any requests it is invoked with.
- Parameters:
app – The ASGI application callable to forward requests to.
default_span_details – Callback which should return a string and a tuple, representing the desired default span name and a dictionary with any additional span attributes to set. Optional: Defaults to get_default_span_details.
server_request_hook (
Optional
[Callable
[[Span
,Dict
[str
,Any
]],None
]]) – Optional callback which is called with the server span and ASGI scope object for every incoming request.client_request_hook (
Optional
[Callable
[[Span
,Dict
[str
,Any
],Dict
[str
,Any
]],None
]]) – Optional callback which is called with the internal span, and ASGI scope and event which are sent as dictionaries for when the method receive is called.client_response_hook (
Optional
[Callable
[[Span
,Dict
[str
,Any
],Dict
[str
,Any
]],None
]]) – Optional callback which is called with the internal span, and ASGI scope and event which are sent as dictionaries for when the method send is called.tracer_provider – The optional tracer provider to use. If omitted the current globally configured one is used.
meter_provider – The optional meter provider to use. If omitted the current globally configured one is used.
exclude_spans (
Optional
[list
[Literal
['receive'
,'send'
]]]) – Optionally exclude HTTP send and/or receive spans from the trace.