[Proposal] Instrumentation for aiogram(Telegram Bot Framework)
feature-request
### What problem do you want to solve?
Now there isn't any possibility to deep dive into telegram bots execution flow: instrumentors like aiohttp-client, asgi(fastapi) show only top-level methods like starting handling, sending POST to telegram API and so on without additional context like aiogram handler name, middlewares trace, etc.
## Example
Simple code:
```python
@dp.message()
async def echo(message: aiogram_types.Message) -> None:
if not message.text:
return
await asyncio.sleep(0.1)
await message.answer(message.text)
class SleepMiddleware(BaseMiddleware):
async def __call__(self, handler, event, data):
await asyncio.sleep(0.5)
return await handler(event, data)
dp.message.middleware(SleepMiddleware())
```
I want to represent tracing as on this picture(I made this preview manually)
<img width="1918" height="511" alt="Image" src="https://github.com/user-attachments/assets/f5388aab-0423-4157-bb91-d1380794555d" />
### Describe the solution you'd like
I suggest add telemetry for telegram bots:
- trace each middleware
- trace handlers and filters
- show http requests to telegram API(e.g. `POST api.telegram.org/bot.../sendMessage`) as obvious sendMessage request
- show the aiogram-handler name
- both webhook and polling support
I would like to implement this as a new package opentelemetry-instrumentation-aiogram.
### Describe alternatives you've considered
Manual registration like
```python
@dp.message()
async def echo(message: types.Message) -> None:
with tracer.start_as_current_span("echo"):
await message.answer(message.text)
class SleepMiddleware(BaseMiddleware):
async def __call__(self, handler, event, data):
with tracer.start_as_current_span("SleepMiddleware"):
await asyncio.sleep(0.5)
return await handler(event, data)
```
In my opinion this approach generates a lot of boilerplate.
### Additional Context
`aiogram` is the most popular asynchronous framework for Telegram Bot API in the Python ecosystem (5k+ stars). Currently, there is no official instrumentation for it in `opentelemetry-python-contrib.`
**I am going to work on this myself.**
Architecture draft:
- wrap each middleware by patching `aiogram.dispatcher.middlewares.MiddlewareManager.wrap_middlewares` using wrapt
- use AioHttpClientInstrumentor with `request_hook` to catch requests to telegram API and update trace context
### Would you like to implement a fix?
Yes
### Tip
<sub>[React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>
1 条评论