What happened?
When attempting to use the opentelemetry-instrumentation-asgi package in a FastAPI application, an ImportError occurs due to missing imports for ClientRequestHook, ClientResponseHook, and ServerRequestHook.
with the package pip install fastapi opentelemetry-instrumentation-asgi
Expected Result
The application should run without any import errors, and the OpenTelemetry ASGI middleware should be applied to the FastAPI application.
Actual Result
ImportError: cannot import name 'ClientRequestHook' from 'opentelemetry.instrumentation.asgi'
Additional context
Additional context
The ClientRequestHook, ClientResponseHook, and ServerRequestHook are not available in the opentelemetry-instrumentation-asgi package, causing the import error.
Solution
To resolve this issue, you can remove the imports for ClientRequestHook, ClientResponseHook, and ServerRequestHook and adjust the middleware setup accordingly. Here is the updated code:
Describe your environment
name: opentelemetry channels:
What happened?
What happened? When attempting to use the opentelemetry-instrumentation-asgi package in a FastAPI application, an ImportError occurs due to missing imports for ClientRequestHook, ClientResponseHook, and ServerRequestHook.
https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py
Steps to Reproduce
Run the file https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py
with the package pip install fastapi opentelemetry-instrumentation-asgi
Expected Result
The application should run without any import errors, and the OpenTelemetry ASGI middleware should be applied to the FastAPI application.
Actual Result
ImportError: cannot import name 'ClientRequestHook' from 'opentelemetry.instrumentation.asgi'
Additional context
Additional context The ClientRequestHook, ClientResponseHook, and ServerRequestHook are not available in the opentelemetry-instrumentation-asgi package, causing the import error.
Solution To resolve this issue, you can remove the imports for ClientRequestHook, ClientResponseHook, and ServerRequestHook and adjust the middleware setup accordingly. Here is the updated code:
// ... existing code ... from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware // ... existing code ...
class FastAPIInstrumentor(BaseInstrumentor): // ... existing code ...
class _InstrumentedFastAPI(fastapi.FastAPI): _tracer_provider = None _meter_provider = None _excluded_urls = None _server_request_hook = None _client_request_hook = None _client_response_hook = None _instrumented_fastapi_apps = set()
Would you like to implement a fix?
Yes