Registry /
observability / opentelemetry-instrumentation-asyncio
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.
Install & Compatibility
Where this runs
tested against v0.63b1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.925 runs
installs and imports cleanly · install 0.0s · import 0.458s · 52MB
glibcpy 3.10–3.925 runs
installs and imports cleanly · install 5.0s · import 0.422s · 50MB
49MB installed
● package 49MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
AsyncioInstrumentor
✓ from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor
The primary class to enable asyncio instrumentation.
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].
import asyncio
import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor
# Configure OpenTelemetry TracerProvider
resource = Resource.create({"service.name": "asyncio-example"})
provider = TracerProvider(resource=resource)
# Use os.environ.get for OTLP endpoint in quickstart
otlp_exporter = OTLPSpanExporter(
endpoint=os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT_GRPC', 'http://localhost:4317'),
insecure=True # Set to False for production with HTTPS
)
span_processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(span_processor)
trace.set_tracer_provider(provider)
# Instrument asyncio
AsyncioInstrumentor().instrument()
tracer = trace.get_tracer(__name__)
async def some_async_task(task_id: int):
with tracer.start_as_current_span(f"some_async_task-{task_id}"):
print(f"Task {task_id}: Starting...")
await asyncio.sleep(0.05) # Simulated async I/O
print(f"Task {task_id}: Done.")
async def main():
print("Main application starting...")
await asyncio.gather(
some_async_task(1),
some_async_task(2),
some_async_task(3)
)
print("Main application finished.")
if __name__ == "__main__":
# Example of configuring tracing for specific coroutines via environment variable
# os.environ['OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE'] = 'some_async_task'
asyncio.run(main())
# Ensure all spans are exported before exiting
provider.shutdown()
opentelemetry-instrument --version
Debug
Known issues
betaAs 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.fixAlways review the changelog for each new release in the `opentelemetry-python-contrib` repository before upgrading to identify potential breaking changes or necessary adaptations [19].
affects: All versions < 1.0.0
gotchaGranular 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.fixEnsure 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].
affects: All versions
gotchaOpenTelemetry'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.fixTrust `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].
affects: All versions
gotchaWhen 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.fixConsider 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].
affects: All versions
Audit
Dependencies
pythonrequiredRequired Python version.
opentelemetry-apirequiredCore OpenTelemetry API for defining telemetry.
opentelemetry-sdkrequiredCore OpenTelemetry SDK for processing and exporting telemetry.
wraptrequiredUsed for function wrapping and dynamic instrumentation.