用 Prometheus 监控 Python 应用:新手实战

Python 应用接入 Prometheus:prometheus-client 库安装、/metrics 端点暴露、Counter/Gauge/Histogram 埋点、Flask/FastAPI 中间件集成与生产注意事项。

最佳实践
用 Prometheus 监控 Python 应用:新手实战技术指南封面

Python 应用接入 Prometheus 用官方客户端库 prometheus-client,十分钟就能让应用暴露标准指标端点。本文走完从安装到生产部署的完整流程。

安装与最小示例

pip install prometheus-client
from prometheus_client import start_http_server, Counter
import random, time

# 定义指标
REQUEST_COUNT = Counter('app_requests_total', 'Total requests', ['method', 'endpoint'])

def handle_request():
    REQUEST_COUNT.labels(method='GET', endpoint='/api').inc()

if __name__ == '__main__':
    start_http_server(8000)          # 在 8000 端口暴露 /metrics
    while True:
        handle_request()
        time.sleep(random.random())

访问 http://localhost:8000/metrics 可见指标输出,包括默认的 Python 运行时指标(GC 对象数等)。

三种核心指标类型

from prometheus_client import Counter, Gauge, Histogram

# Counter:只增计数(请求数、错误数)
errors = Counter('app_errors_total', 'Total errors', ['type'])

# Gauge:瞬时值(队列深度、在线连接)
queue_depth = Gauge('job_queue_depth', 'Current queue depth')
queue_depth.set(42)   # 或 .inc()/.dec()

# Histogram:延迟分布
latency = Histogram('request_duration_seconds', 'Request latency',
                    buckets=[0.01, 0.05, 0.1, 0.5, 1, 5])

with latency.time():          # 用上下文管理器自动计时
    do_something()

Web 框架集成

Flask

from flask import Flask
from prometheus_client import Counter, Histogram, generate_latest

app = Flask(__name__)
REQS = Counter('http_requests_total', 'Requests', ['method', 'endpoint', 'status'])
LAT = Histogram('http_request_duration_seconds', 'Latency', ['endpoint'])

@app.before_request
def before(): request._start_time = time.time()

@app.after_request
def after(resp):
    REQS.labels(request.method, request.path, resp.status_code).inc()
    return resp

@app.route('/metrics')
def metrics():
    return generate_latest(), 200, {'Content-Type': 'text/plain'}

FastAPI 更省事——直接用 prometheus-fastapi-instrumentator 中间件,一行挂载。

生产环境注意事项

  1. 多进程问题(Gunicorn/uWSGI):每个 worker 各自计数会互相覆盖。prometheus-client 有多进程模式(设 PROMETHEUS_MULTIPROC_DIR 环境变量),或改用 aggregator;
  2. 标签基数:endpoint 标签用路由模板(/users/{id})而非原始路径;
  3. /metrics 端点别暴露公网:只对内网/Prometheus 服务器开放。

观测云对照

Python 服务更省力的路径是观测云 APM 探针:请求速率、错误率、延迟分布、慢请求追踪全部自动采集,不用手写埋点;已有的 prometheus-client 自定义指标可以由 DataKit 抓取汇聚,业务指标与应用性能数据在同一平台联动分析,告警一处配置。

常见问题(FAQ)

Q:Celery 任务怎么监控?
A:任务里埋点(处理数 Counter、耗时 Histogram),暴露方式用 start_http_server 或 textfile;监控队列积压用 Redis/RabbitMQ 的 exporter。

Q:能看到 P99 延迟吗?
A:Histogram 类型暴露 bucket 后,PromQL 里 histogram_quantile(0.99, ...) 即可。Summary 类型也行但不可跨实例聚合。

Q:多进程模式的指标文件要清理吗?
A:要。worker 退出会留下残留文件,定期清理 PROMETHEUS_MULTIPROC_DIR 里的孤儿文件,新版客户端有 marks_process_dead 类辅助接口。

获取专属方案

联系我们

加入社区

微信扫码
加入官方交流群

立即体验

在线开通,按量计费,真正的云服务!

立即开始

选择观测云版本

代码托管平台