{"id":2152,"library":"opentelemetry-instrumentation-asyncio","title":"OpenTelemetry Asyncio Instrumentation","description":"The `opentelemetry-instrumentation-asyncio` package provides OpenTelemetry tracing and metrics for applications built with Python's `asyncio` library. It enables the collection of duration and counts for coroutines and futures, even if no explicit tracing is configured. This library is part of the `opentelemetry-python-contrib` project, with the current version being `0.62b0`, indicating it is actively developed and in a pre-release (beta) stage.","status":"active","version":"0.62b0","language":"en","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-asyncio","tags":["opentelemetry","asyncio","instrumentation","observability","tracing","metrics","beta","python"],"install":[{"cmd":"pip install opentelemetry-instrumentation-asyncio opentelemetry-sdk opentelemetry-exporter-otlp","lang":"bash","label":"Install core, SDK, exporter, and asyncio instrumentation"}],"dependencies":[{"reason":"Required Python version.","package":"python","optional":false},{"reason":"Core OpenTelemetry API for defining telemetry.","package":"opentelemetry-api","optional":false},{"reason":"Core OpenTelemetry SDK for processing and exporting telemetry.","package":"opentelemetry-sdk","optional":false},{"reason":"Used for function wrapping and dynamic instrumentation.","package":"wrapt","optional":false}],"imports":[{"note":"The primary class to enable asyncio instrumentation.","symbol":"AsyncioInstrumentor","correct":"from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor"}],"quickstart":{"code":"import asyncio\nimport os\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\nfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter\nfrom opentelemetry.instrumentation.asyncio import AsyncioInstrumentor\n\n# Configure OpenTelemetry TracerProvider\nresource = Resource.create({\"service.name\": \"asyncio-example\"})\nprovider = TracerProvider(resource=resource)\n# Use os.environ.get for OTLP endpoint in quickstart\notlp_exporter = OTLPSpanExporter(\n    endpoint=os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT_GRPC', 'http://localhost:4317'),\n    insecure=True # Set to False for production with HTTPS\n)\nspan_processor = BatchSpanProcessor(otlp_exporter)\nprovider.add_span_processor(span_processor)\ntrace.set_tracer_provider(provider)\n\n# Instrument asyncio\nAsyncioInstrumentor().instrument()\n\ntracer = trace.get_tracer(__name__)\n\nasync def some_async_task(task_id: int):\n    with tracer.start_as_current_span(f\"some_async_task-{task_id}\"):\n        print(f\"Task {task_id}: Starting...\")\n        await asyncio.sleep(0.05) # Simulated async I/O\n        print(f\"Task {task_id}: Done.\")\n\nasync def main():\n    print(\"Main application starting...\")\n    await asyncio.gather(\n        some_async_task(1),\n        some_async_task(2),\n        some_async_task(3)\n    )\n    print(\"Main application finished.\")\n\nif __name__ == \"__main__\":\n    # Example of configuring tracing for specific coroutines via environment variable\n    # os.environ['OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE'] = 'some_async_task'\n    asyncio.run(main())\n    # Ensure all spans are exported before exiting\n    provider.shutdown()","lang":"python","description":"This quickstart demonstrates how to instrument an `asyncio` application using `AsyncioInstrumentor`. It sets up a basic OpenTelemetry `TracerProvider` with an OTLP exporter, then enables the `asyncio` instrumentation. The example includes multiple concurrent `asyncio` tasks to show how traces are captured across `await` boundaries. Environment variables like `OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE` can be used for more granular control over which coroutines are traced [1, 2, 5]."},"warnings":[{"fix":"Always review the changelog for each new release in the `opentelemetry-python-contrib` repository before upgrading to identify potential breaking changes or necessary adaptations [19].","message":"As a beta release (`0.62b0`), the API and behavior of `opentelemetry-instrumentation-asyncio` are subject to change without strict adherence to semantic versioning. Breaking changes may occur in future minor or patch releases until a stable `1.0.0` version is reached.","severity":"beta","affected_versions":"All versions < 1.0.0"},{"fix":"Ensure you explicitly set environment variables such as `OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE` (for specific coroutines), `OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE` (for `to_thread` calls), and `OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED` (for tracing futures) as needed. Refer to the documentation for available options [1, 2].","message":"Granular control over which `asyncio` components are instrumented often relies on environment variables. Forgetting to set these or misconfiguring them can lead to unexpected tracing behavior or a lack of telemetry.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Trust `asyncio`'s automatic context propagation for most cases. Create spans *within* coroutines, not around them, to ensure they execute in the correct async context. Be cautious with explicit context manipulation unless you fully understand its implications on trace propagation [5, 12].","message":"OpenTelemetry's context propagation in Python relies on `contextvars`, which works seamlessly with `asyncio`'s task-local context across `await` boundaries. However, improper use of `asyncio` features or manually managing contexts can break trace relationships.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Consider using programmatic auto-instrumentation or ensuring that OpenTelemetry is initialized *after* forking, or use a single-worker deployment strategy. Consult the OpenTelemetry Python troubleshooting guide for workarounds related to pre-fork servers [15].","message":"When deploying `asyncio` applications with pre-forking servers (e.g., Gunicorn with multiple worker processes), OpenTelemetry's SDK components, particularly those involving background threads (like `PeriodicExportingMetricReader`), can experience inconsistencies or deadlocks after forking. This is a general OpenTelemetry Python SDK issue.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}