深色模式
应用自定义指标 /metrics
监控不只是看机器,更要看业务。本文用 Python 写个最小 demo,让你的应用也能被 Prometheus 抓取。
适用环境
- 有 Python 3.8+ 环境
- 已部署 Prometheus 可接入新 target
bash
python3 --version
pip3 --version1
2
2
操作步骤
1. 安装客户端库
bash
pip3 install prometheus-client1
2. 写一个暴露指标的 demo
python
from prometheus_client import start_http_server, Counter, Gauge
import random, time
# 计数器:累计请求数
REQ = Counter('demo_requests_total', 'Total requests')
# 仪表盘:当前队列长度
QUEUE = Gauge('demo_queue_length', 'Current queue length')
if __name__ == '__main__':
start_http_server(8000) # 暴露 /metrics 在 8000 端口
while True:
REQ.inc()
QUEUE.set(random.randint(0, 100))
time.sleep(1)1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
3. 运行并接入 Prometheus
bash
python3 demo_metrics.py &1
yaml
- job_name: demo
static_configs:
- targets: ['localhost:8000']1
2
3
2
3
验证
bash
curl -s http://localhost:8000/metrics | grep '^demo_'1
promql
rate(demo_requests_total[1m])
demo_queue_length1
2
2
常见坑
指标名加业务前缀
避免和系统指标重名,建议 服务名_指标名_类型,如 order_paid_total。
不要在请求路径里计数
start_http_server 是独立端口,业务逻辑里只调 inc()/set(),别把采集耦合进主流程。