Prometheus默认收集系统指标(CPU、内存、磁盘),但业务健康的核心是业务指标——订单成功率、支付失败数、用户活跃度。本文从Exporter开发到SLO告警,构建完整的业务监控体系。
一、四种Prometheus指标类型
<code">Counter(计数器):只增不减,统计累计数量 示例:http_requests_total, orders_created_total 用途:QPS = rate(requests_total[5m]) Gauge(仪表盘):可增可减,当前状态值 示例:active_users, queue_size, memory_bytes 用途:直接使用当前值 Histogram(直方图):观察值的分布(延迟分布) 示例:http_request_duration_seconds 用途:计算P99延迟 = histogram_quantile(0.99, ...) Summary(摘要):客户端计算的百分位数 示例:go_gc_duration_seconds 用途:已知百分位数,但不需要聚合计算
二、Python自定义Exporter开发
<code"># pip install prometheus-client --break-system-packages
# business_exporter.py
from prometheus_client import (
Counter, Gauge, Histogram, Summary,
start_http_server, CollectorRegistry
)
import pymysql
import redis
import time
import threading
# 创建指标(全局单例)
# 订单相关指标
ORDERS_TOTAL = Counter(
'orders_created_total',
'创建的订单总数',
['status', 'payment_method'], # 标签:按状态和支付方式细分
)
ORDER_AMOUNT = Histogram(
'order_amount_yuan',
'订单金额分布(元)',
buckets=[10, 50, 100, 200, 500, 1000, 2000, 5000], # 自定义桶
)
# 用户相关指标
ACTIVE_USERS = Gauge(
'active_users_count',
'活跃用户数(最近24小时有操作)',
)
# API延迟指标
API_LATENCY = Histogram(
'api_request_duration_seconds',
'API请求延迟',
['endpoint', 'method'],
buckets=[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
)
# 业务错误计数
BUSINESS_ERRORS = Counter(
'business_errors_total',
'业务错误总数',
['error_type', 'service'],
)
# 队列积压
QUEUE_SIZE = Gauge(
'task_queue_size',
'任务队列积压数量',
['queue_name'],
)
# 数据库连接池
DB_POOL_SIZE = Gauge(
'db_connection_pool_size',
'数据库连接池使用情况',
['state'], # state: active, idle
)
class BusinessMetricsCollector:
"""从数据库和Redis收集业务指标"""
def __init__(self):
self.db_config = {
'host': '127.0.0.1',
'user': 'metrics_readonly',
'password': '只读密码',
'database': 'shop_db',
'charset': 'utf8mb4',
}
self.redis = redis.Redis(host='127.0.0.1', password='Redis密码')
def collect_order_metrics(self):
"""从数据库收集最近5分钟的订单指标"""
try:
conn = pymysql.connect(**self.db_config)
with conn.cursor(pymysql.cursors.DictCursor) as cursor:
# 最近5分钟的订单(避免全表扫描)
cursor.execute("""
SELECT status, payment_method, COUNT(*) AS cnt, AVG(amount) AS avg_amount
FROM orders
WHERE created_at >= NOW() - INTERVAL 5 MINUTE
GROUP BY status, payment_method
""")
for row in cursor.fetchall():
ORDERS_TOTAL.labels(
status=row['status'],
payment_method=row['payment_method'] or 'unknown'
).inc(row['cnt'])
# 活跃用户数
cursor.execute("""
SELECT COUNT(DISTINCT user_id) AS cnt
FROM user_actions
WHERE action_time >= NOW() - INTERVAL 24 HOUR
""")
row = cursor.fetchone()
ACTIVE_USERS.set(row['cnt'])
conn.close()
except Exception as e:
BUSINESS_ERRORS.labels(error_type='db_query', service='metrics_collector').inc()
print(f"数据库指标收集失败:{e}")
def collect_queue_metrics(self):
"""从Redis收集队列积压"""
try:
for queue_name in ['email', 'sms', 'push_notification', 'report']:
size = self.redis.llen(f'queue:{queue_name}')
QUEUE_SIZE.labels(queue_name=queue_name).set(size)
except Exception as e:
BUSINESS_ERRORS.labels(error_type='redis_error', service='metrics_collector').inc()
def collect_all(self):
"""收集所有指标(在后台线程中定期运行)"""
while True:
self.collect_order_metrics()
self.collect_queue_metrics()
time.sleep(30) # 每30秒收集一次
if __name__ == '__main__':
collector = BusinessMetricsCollector()
# 在后台线程收集指标
thread = threading.Thread(target=collector.collect_all, daemon=True)
thread.start()
# 启动Prometheus指标HTTP端点
start_http_server(9101)
print("Business Exporter 运行在 http://0.0.0.0:9101/metrics")
# 主线程等待
thread.join()
三、在应用代码中埋点
<code"># Flask/FastAPI中直接使用指标
from prometheus_client import Counter, Histogram
import time
REQUEST_COUNT = Counter('http_requests_total', 'HTTP请求总数', ['method', 'endpoint', 'status'])
REQUEST_LATENCY = Histogram('http_request_duration_seconds', '请求延迟', ['endpoint'])
# Flask中间件
@app.before_request
def start_timer():
g.start = time.time()
@app.after_request
def record_metrics(response):
latency = time.time() - g.start
REQUEST_LATENCY.labels(endpoint=request.path).observe(latency)
REQUEST_COUNT.labels(
method=request.method,
endpoint=request.path,
status=response.status_code
).inc()
return response
# 订单创建时手动埋点
def create_order(user_id, amount, payment_method):
try:
order = Order.create(user_id=user_id, amount=amount)
ORDERS_TOTAL.labels(status='success', payment_method=payment_method).inc()
ORDER_AMOUNT.observe(amount)
return order
except PaymentError as e:
ORDERS_TOTAL.labels(status='payment_failed', payment_method=payment_method).inc()
BUSINESS_ERRORS.labels(error_type='payment', service='order').inc()
raise
四、PromQL告警规则
<code"># /etc/prometheus/rules/business-alerts.yml
groups:
- name: business
rules:
# 订单支付失败率告警(5分钟内失败率>5%)
- alert: HighPaymentFailureRate
expr: |
rate(orders_created_total{status="payment_failed"}[5m])
/
rate(orders_created_total[5m]) > 0.05
for: 2m # 持续2分钟才触发(防抖)
labels:
severity: critical
team: payment
annotations:
summary: "支付失败率过高"
description: "过去5分钟支付失败率 {{ $value | humanizePercentage }}(阈值5%)"
runbook: "https://wiki.yourdomain.com/runbooks/payment-failure"
# API P99延迟告警
- alert: HighApiLatency
expr: |
histogram_quantile(0.99,
rate(http_request_duration_seconds_bucket{endpoint="/api/checkout"}[5m])
) > 2.0
for: 5m
labels:
severity: warning
annotations:
summary: "/api/checkout P99延迟超过2秒"
description: "当前P99 = {{ $value | humanizeDuration }}"
# 队列积压告警
- alert: TaskQueueBacklog
expr: task_queue_size{queue_name="email"} > 10000
for: 3m
labels:
severity: warning
annotations:
summary: "邮件队列积压过多"
description: "邮件队列积压 {{ $value }} 条(阈值10000)"
# 活跃用户异常下降(可能业务故障)
- alert: ActiveUsersDropped
expr: |
(active_users_count - active_users_count offset 1h)
/ active_users_count offset 1h < -0.3
for: 15m
labels:
severity: critical
annotations:
summary: "活跃用户数急剧下降"
description: "较1小时前下降 {{ $value | humanizePercentage }}"
五、SLO(服务水平目标)设定
<code"># SLO指标:可用性和延迟目标
# SLO = 99.9%(每月允许43分钟停机)
# /etc/prometheus/rules/slo.yml
groups:
- name: slo
rules:
# 可用性SLI:非5xx请求占比
- record: slo:availability:ratio5m
expr: |
1 - (
rate(http_requests_total{status=~"5.."}[5m])
/
rate(http_requests_total[5m])
)
# 延迟SLI:P99<500ms的请求占比
- record: slo:latency:ratio5m
expr: |
histogram_quantile(0.99,
rate(http_request_duration_seconds_bucket[5m])
) <= 0.5 # SLO燃烧率告警(Error Budget Burn Rate) # 如果在1小时内的错误率是月度预算的14倍,说明Error Budget快耗尽 - alert: SLOBurnRateHigh expr: | ( rate(http_requests_total{status=~"5.."}[1h]) / rate(http_requests_total[1h]) ) > 14 * (1 - 0.999) # 14 × 月度错误率阈值
for: 5m
labels:
severity: critical
annotations:
summary: "SLO燃烧率过高,Error Budget快耗尽"
description: "当前燃烧率 {{ $value | humanizePercentage }}"
六、Grafana仪表盘
<code"># 关键业务仪表盘面板(Grafana)
# 面板1:实时QPS
rate(http_requests_total[1m]) by (endpoint)
# 面板2:支付成功率(最近1小时)
sum(increase(orders_created_total{status="success"}[1h]))
/ sum(increase(orders_created_total[1h])) * 100
# 面板3:API P50/P95/P99延迟
histogram_quantile(0.50, rate(http_request_duration_seconds_bucket[5m]))
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))
# 面板4:活跃用户趋势
active_users_count
# 面板5:队列积压
task_queue_size by (queue_name)
# 面板6:SLO仪表(时间范围:30天)
1 - (
increase(http_requests_total{status=~"5.."}[30d])
/ increase(http_requests_total[30d])
) * 100
七、总结
业务指标监控的价值远超系统指标——CPU100%和支付失败率都是问题,但后者更直接影响收入。Prometheus的四种指标类型覆盖所有监控场景,SLO告警基于”错误预算消耗率”而非固定阈值,更符合生产实际。IDC.Net的香港VPS内网互通,Prometheus服务器可以同时抓取多台业务服务器的指标,构建统一的监控大盘。
