Async Code
Trace async functions and capture unhandled asyncio task exceptions.
TraceKit works out of the box with async def functions and asyncio event loops.
What it does
@tracekit.tracedetects coroutine functions automatically viainspect.iscoroutinefunctionand awaits them while timing the full coroutine execution.tracekit.install_asyncio_hook(loop)attaches an exception handler to your event loop so unhandled task exceptions are captured while preserving Python's default handler.- Scope data (
set_user,set_tag,add_breadcrumb) usescontextvars, so concurrent tasks never leak context into each other.
Minimal example
async_app.py
import asyncioimport tracekit
tracekit.init(output="console", environment="production")
@tracekit.traceasync def fetch_user(user_id: int) -> dict: await asyncio.sleep(0.02) return {"id": user_id, "name": "Alice"}
async def main() -> None: loop = asyncio.get_running_loop() tracekit.install_asyncio_hook(loop)
user = await fetch_user(1) print("Fetched:", user["name"])
asyncio.run(main())tracekit.flush()Expected output
output
Fetched: Alice[TraceKit 2026-11-28 09:56:01] SPAN fetch_user (21.34ms) okBackground tasks
When you spawn fire-and-forget tasks with asyncio.create_task(), unhandled exceptions inside those tasks are routed to the loop's exception handler when the task is garbage-collected. Installing tracekit.install_asyncio_hook(loop) ensures TraceKit captures them.
Common mistakes
- Calling
install_asyncio_hook()beforeinit(): You can call it afterinit(), once a loop is running (asyncio.get_running_loop()) or afterasyncio.new_event_loop(). - Calling
install_asyncio_hook()with no running loop: If no event loop exists yet,install_asyncio_hook(None)is a silent no-op and won't crash your app.