Skip to content

Improve asgi instrumentation example #3576

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,38 @@ async def hello():

.. code-block:: python

def server_request_hook(span: Span, scope: dict[str, Any]):
from opentelemetry.trace import Span
from typing import Any
from asgiref.typing import Scope, ASGIReceiveEvent, ASGISendEvent
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware

async def application(scope: Scope, receive: ASGIReceiveEvent, send: ASGISendEvent):
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})

await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})

def server_request_hook(span: Span, scope: Scope):
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]):
def client_request_hook(span: Span, scope: Scope, 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]):
def client_response_hook(span: Span, scope: Scope, 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)
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
*****************************************
Expand Down
Loading