diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py index 8bf9c71aed..80682dc5bb 100644 --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -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 *****************************************