You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prometheus是否有适配异步场景的官方客户端库?

关于aiohttp服务接入Prometheus监控的方案说明

1. 官方客户端异步支持情况

官方维护的prometheus-client Python库从v0.14.0版本开始已经原生兼容异步运行环境,不存在官方没有适配的问题,你之前没找到相关信息可能是没注意版本更新说明。
该版本之后的官方客户端内置了适配异步环境的能力,可直接集成到aiohttp服务的路由体系中,所有指标操作都不会阻塞异步事件循环。

2. 具体落地方案

基础集成步骤

  • 首先安装对应版本依赖:pip install prometheus-client>=0.14.0 aiohttp
  • 直接在aiohttp服务中注册监控路由和统计中间件即可,参考代码如下:
from aiohttp import web
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, Counter, Histogram

# 自定义业务监控指标示例
REQUEST_COUNT = Counter('aiohttp_request_total', '服务总请求量', ['method', 'endpoint', 'status'])
REQUEST_LATENCY = Histogram('aiohttp_request_latency_seconds', '请求延迟分布', ['endpoint'])

# Prometheus指标拉取接口
async def metrics_handler(request):
    return web.Response(
        body=generate_latest(),
        content_type=CONTENT_TYPE_LATEST
    )

# 全局请求统计中间件
@web.middleware
async def metrics_middleware(request, handler):
    endpoint = request.path
    with REQUEST_LATENCY.labels(endpoint=endpoint).time():
        try:
            response = await handler(request)
            status = response.status
            return response
        finally:
            REQUEST_COUNT.labels(
                method=request.method,
                endpoint=endpoint,
                status=status if 'status' in locals() else 500
            ).inc()

# 注册路由和中间件
app = web.Application(middlewares=[metrics_middleware])
app.add_routes([web.get('/metrics', metrics_handler)])
# 此处添加你的业务路由
if __name__ == '__main__':
    web.run_app(app, port=8080)

生产环境注意事项

  • 如果你采用多worker进程部署aiohttp服务,需要提前设置环境变量PROMETHEUS_MULTIPROC_DIR指向一个可读写的空临时目录,官方客户端会自动聚合所有进程的监控数据,避免指标遗漏。
  • 所有指标的增减、计时操作都是无阻塞、线程安全的,可以直接在异步协程中调用,不需要额外加异步包装。

3. 可选第三方适配库

如果你的业务依赖限制无法升级prometheus-client到0.14.0及以上版本,可以选择社区维护的aiohttp-prometheus库做兼容,不过该库停止更新时间较久,更推荐优先使用官方原生的异步支持能力。

内容的提问来源于stack exchange,提问作者dmc94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 04:39:00