直接用 prometheus_client.make_asgi_app() 会报 404 是因为 fastapi 不自动挂载该 asgi 应用,需显式调用 app.mount("/metrics", metrics_app);误用 include_router 或路径不以 / 开头会导致失败。

为什么直接用 prometheus_client 的 make_asgi_app() 会报错 404?
FastAPI 默认不自动挂载 Prometheus 的指标端点(/metrics),即使你调用了 prometheus_client.make_asgi_app(),它返回的是一个 ASGI 应用实例,但没注册进 FastAPI 的路由系统。常见现象是访问 /metrics 返回 404,或者启动时报 TypeError: object of type 'ASGIApp' has no len()——那是因为误把它当成了中间件或路由处理器直接传给了 app.mount() 或 app.include_router()。
正确做法是用 app.mount() 挂载,且路径必须以 / 开头、不能带变量或通配符:
from prometheus_client import make_asgi_app
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
注意:make_asgi_app() 返回的不是 FastAPI 的 APIRouter,不能用 include_router;也不能漏掉引号里的斜杠,写成 app.mount("metrics", ...) 会导致路径错位。
如何在 FastAPI 请求生命周期中自动记录 HTTP 请求延迟和状态码?
Prometheus 客户端本身不自动采集 HTTP 指标,得自己加中间件。核心是用 Counter 和 Histogram 记录请求计数、延迟分布,并在响应返回前完成观测。
关键点:
-
Histogram的buckets建议覆盖常见延迟范围,比如(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0),单位是秒 - 标签(
labelnames)至少包含method、status_code、path,其中path要做标准化(如把/users/123归一为/users/{id}),否则指标维度爆炸 - 中间件里必须用
await call_next(request),不能丢掉 await,否则响应体可能为空或超时
示例片段(不依赖第三方库):
from prometheus_client import Counter, Histogram
from fastapi import Request, Response
import time
<p>REQUEST_COUNT = Counter(
"http_requests_total",
"Total HTTP Requests",
["method", "status_code", "path"]
)
REQUEST_LATENCY = Histogram(
"http_request_duration_seconds",
"HTTP Request Duration",
["method", "path"],
buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0)
)</p><p>@app.middleware("http")
async def metrics_middleware(request: Request, call_next):
start_time = time.time()
try:
response = await call_next(request)
status_code = response.status_code
except Exception as e:
status_code = 500
raise e
finally:
process_time = time.time() - start_time
path = request.url.path
method = request.method</p><h1>简单路径归一化(实际建议用更健壮的路由匹配)</h1><pre class="brush:python;toolbar:false;"> if path.isdigit():
path = "/{id}"
elif "/user/" in path:
path = "/user/{id}"
REQUEST_COUNT.labels(method=method, status_code=status_code, path=path).inc()
REQUEST_LATENCY.labels(method=method, path=path).observe(process_time)
多个 FastAPI 实例共用同一个 Prometheus registry 时要注意什么?
默认情况下 prometheus_client 使用全局 registry(REGISTRY),多进程部署(如用 uvicorn --workers 4)时,各 worker 进程会各自维护一份指标,导致 /metrics 返回的数据不一致甚至崩溃(因为并发写 registry 非线程安全)。
Python 3.14.2是Python编程语言在2025年12月5日发布的稳定版本,属于3.14系列的第二个维护更新。该版本包含了18项修复,重点解决了多进程、数据类及正则表达式等模块的回归问题,并修复了CVE-2025-12084等安全漏洞。此版本标志着自由线程模式(移除GIL)正式获得官方支持,是Python发展的重要里程碑。
解决方向只有两个:
- 用
prometheus-client的multiprocess模式:需设置环境变量PROMETHEUS_MULTIPROC_DIR指向一个可写的临时目录,并在应用启动前调用prometheus_client.multiprocess.MultiProcessCollector(REGISTRY) - 改用单进程部署(如只开 1 个 worker),适合开发或低流量场景;但生产环境通常不推荐
注意:multiprocess 模式下,/metrics 端点必须用 make_wsgi_app() + WSGI server(如 Gunicorn),而 FastAPI 是 ASGI。所以目前没有开箱即用的多进程 ASGI 支持——你得自己封装一层 WSGI 兼容逻辑,或改用 starlette_exporter 这类专为 ASGI 设计的库。
为什么自定义指标在 /metrics 里查不到?
最常见原因是指标对象(Gauge、Counter 等)定义在函数作用域内,每次调用都新建一个实例,导致 registry 里没注册成功;或者用了不同 registry 实例,而 make_asgi_app() 挂载的是默认 registry。
务必确保:
- 所有指标变量定义在模块顶层(global scope),不要放在路由函数或中间件内部
- 如果手动创建了新 registry(如
Registry()),就得显式传给make_asgi_app(registry=my_registry) - 避免重复命名:同名指标(相同名称+类型)第二次注册会抛
ValueError: Duplicated timeseries in CollectorRegistry
例如,错误写法:
@app.get("/health")
def health():
gauge = Gauge("my_custom_gauge", "A gauge") # ❌ 每次请求都新建,不会被采集
gauge.set(1)
return {"status": "ok"}
正确写法:
MY_CUSTOM_GAUGE = Gauge("my_custom_gauge", "A gauge") # ✅ 模块级定义
<p>@app.get("/health")
def health():
MY_CUSTOM_GAUGE.set(1)
return {"status": "ok"}</p>
复杂点在于指标生命周期和异步任务的协同——比如后台 Celery 任务更新的 Gauge,必须和 FastAPI 主进程共享同一 registry 实例,否则数据就断开了。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










