
文章目录
Prometheus 是一款开源的系统监控和警报工具包。它具有以下特性:
以下通过一个 FastAPI 服务来举例说明
安装pip包
pip install fastapi uvicorn prometheus-client
编写一个简易的服务代码
from fastapi import FastAPI, Response # 导入 FastAPI 应用类和 Response 用于自定义 HTTP 响应
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST # 生成 Prometheus 文本格式及内容类型常量
import time # 用于记录和计算请求耗时
import random # 用于模拟随机成功/失败的响应
app = FastAPI() # 创建 FastAPI 应用实例
# 导入 Prometheus 指标类型:Counter(计数器),Histogram(直方图/分桶)
from prometheus_client import Counter, Histogram
REQUEST_COUNT = Counter('api_requests_total', 'Total API requests', ['status']) # 总请求计数,带 status 标签区分成功/失败
REQUEST_DURATION = Histogram('api_request_duration_seconds', 'API request duration in seconds') # 请求耗时直方图(秒)
@app.middleware("http")
async def add_prometheus_metrics(request, call_next):
start = time.time() # 记录请求开始时间(秒)
response = await call_next(request) # 调用下一个处理器,获取响应
duration = time.time() - start # 计算请求耗时
REQUEST_DURATION.observe(duration) # 将耗时记录到直方图中
return response # 返回响应
@app.get("/api/data")
async def get_data():
success = random.choice([True, False]) # 随机决定成功或失败,模拟业务逻辑
if success:
REQUEST_COUNT.labels(status="success").inc() # 成功计数加 1
return {"code": 0, "msg": "success"} # 返回成功的 JSON
else:
REQUEST_COUNT.labels(status="failure").inc() # 失败计数加 1
return {"code": 1, "msg": "failure"} # 返回失败的 JSON
# ✅ 关键:正确暴露 /metrics 给 Prometheus 抓取
@app.get("/metrics")
async def metrics():
return Response(
content=generate_latest(), # 生成当前所有指标的 prometheus 文本格式内容
media_type=CONTENT_TYPE_LATEST # 设置正确的 Content-Type,通常为 "text/plain; version=0.0.4"
)
启动算法服务
uvicorn fastapi_app:app --host 0.0.0.0 --port 8000
使用podman拉取镜像,跟docker类似
podman pull quay.io/prometheus/prometheus
编写监控配置
[user@MichaelMing ~]$ cat prometheus.yml
global:
scrape_interval: 10s
scrape_configs:
- job_name: 'fastapi_app'
metrics_path: /metrics
scheme: http
static_configs:
- targets: ['localhost:8000'] # ← 关键:用 localhost
rule_files:
- 'alert.rules.yml'
报警配置:最近5分钟错误率超过30%,就会告警
[user@MichaelMing ~]$ cat alert.rules.yml
groups:
- name: api_alerts
rules:
- alert: HighErrorRate
expr: rate(api_requests_total{status="failure"}[5m]) / rate(api_requests_total[5m]) > 0.3
for: 1m
labels:
severity: critical
annotations:
summary: "High error rate on FastAPI API"
description: "Error rate exceeded 30% in the last 5 minutes."
启动监控服务
podman run -d \
--name prometheus \
--network host \
-v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \
-v $(pwd)/alert.rules.yml:/etc/prometheus/alert.rules.yml \
quay.io/prometheus/prometheus
可以看到监控服务已经看到算法启动了 UP了

多次调用算法服务
curl localhost:8000/api/data
然后在监控服务web页面查询 api_requests_total,可以查看任务成功和失败次数

查看请求耗时分布 api_request_duration_seconds_bucket

查看报警,FIRING 起火了

本文通过一个完整的示例演示了如何为 FastAPI 应用集成 Prometheus 监控:
prometheus-client 库在 FastAPI 应用中暴露关键指标这种监控方案具有以下优势:
通过这套监控体系,开发者和运维团队能够全面掌握应用的运行状态,快速定位性能瓶颈,及时响应异常情况,为服务的稳定性和可靠性提供有力保障。