简体   繁体   English

导出同步与异步 python 应用程序的普罗米修斯指标

[英]Exporting prometheus metrics of sync vs async python apps

I have a minimal async python server based on aiohttp .我有一个基于aiohttp的最小异步 python 服务器。

It is very straightforward, just a websocket endpoint exposed as in这很简单,只是一个 websocket 端点暴露在

@routes.get('/my_endpoint')
async def my_func(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    return ws

I want to expose as prometheus metrics the request rate (and potentially the error rate).我想将请求率(以及可能的错误率)作为prometheus指标公开。

After performing a brief investigation on the topic, I realised that it seems like there is a distinction between approaching prometheus metrics exposure when it comes to sync vs async apps.在对该主题进行了简短调查后,我意识到在同步异步应用程序方面接近 prometheus 指标公开似乎存在区别。

For my case, where I want a simple request count/rate, is there a reason not to just use the plain' old prometheus python client (eg by simply decorating my_func ?)对于我的情况,我想要一个简单的请求计数/速率,是否有理由不使用普通的旧普罗米修斯 python 客户端(例如,通过简单地装饰my_func ?)

Would the request count actually fail in such a case?在这种情况下,请求计数实际上会失败吗?

The following is based on my understanding on asyncio and the way the official prometheus client describes how it exposes metrics.以下是基于我对asyncio的理解以及官方 prometheus 客户端描述它如何暴露指标的方式。 aiohttp is to be used on top of asyncio . aiohttp将在asyncio之上使用。 Now, asyncio is running something called an "event loop" which runs inside a single thread ( usually the main thread )现在, asyncio正在运行一个称为“事件循环”的东西,它在单个线程( 通常是主线程)内运行

You can look at it as an entity that decides to suspend or execute functions that were assigned to run in the loop.您可以将其视为一个实体,该实体决定暂停或执行被分配在循环中运行的函数。 In your case my_func .在你的情况下my_func For prometheus_client to expose your metrics you will probably need to run it in a different thread要让prometheus_client公开您的指标,您可能需要在不同的线程中运行它

Metrics are usually exposed over HTTP, to be read by the Prometheus server.指标通常通过 HTTP 公开,由 Prometheus 服务器读取。 The easiest way to do this is via start_http_server, which will start a HTTP server in a daemon thread on the given port最简单的方法是通过 start_http_server,它将在给定端口上的守护线程中启动 HTTP 服务器

This is outside "the control of the event loop" which might lead to performance issues and to unexpected behavior as a result.这超出了“事件循环的控制”范围,可能会导致性能问题和意外行为。 So the request count might not fail, but if for some reason its doing some blocking task (I/O) it will block the main thread as well.所以请求计数可能不会失败,但如果由于某种原因它执行一些阻塞任务(I/O),它也会阻塞主线程。 If you'd use the async approach and run it as part of the event loop your blocking task can be awaited and give back the control to the main thread.如果您使用异步方法并将其作为事件循环的一部分运行,则可以等待阻塞任务并将控制权交还给主线程。 There are open source projects that support prometheus in async functions such as aioprometheus and prometheus-async .有一些开源项目在aioprometheusprometheus-async等异步函数中支持 prometheus。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM