Prometheus Exporter:编写自定义指标(Python)
·
Prometheus Exporter:编写自定义指标(Python)
Prometheus 是一个开源的监控和告警系统,它通过 Exporter 来收集和暴露应用程序的自定义指标。自定义指标允许您监控应用程序的特定行为,例如请求次数、处理时间或资源使用情况。在 Python 中,我们可以使用 prometheus_client 库来轻松实现自定义指标的 Exporter。下面,我将逐步指导您如何编写一个简单的自定义指标 Exporter,确保代码结构清晰、易于理解。
步骤 1: 准备工作
在开始编写代码前,需要安装必要的 Python 库。使用 pip 安装 prometheus_client:
pip install prometheus_client
这个库提供了创建和暴露指标的工具,包括 Counter(计数器)、Gauge(仪表盘)、Histogram(直方图)和 Summary(摘要)等类型。
步骤 2: 理解指标类型
在编写自定义指标前,先了解常见的指标类型:
- Counter:用于累计值,如请求总数。它只增不减。
- Gauge:用于可变值,如当前内存使用量。可增可减。
- Histogram:用于采样和分布,如请求延迟。它会自动计算分位数。
- Summary:类似 Histogram,但用于客户端计算的摘要。
在本示例中,我们将创建一个简单的 Counter 指标来监控应用程序的请求次数。
步骤 3: 编写自定义指标代码
创建一个 Python 文件(例如 custom_exporter.py),并添加以下代码。代码分为三部分:
- 定义指标:使用
Counter类创建自定义指标。 - 更新指标:在应用程序逻辑中增加指标值。
- 暴露指标:启动 HTTP 服务器来暴露指标给 Prometheus。
from prometheus_client import start_http_server, Counter
import time
# 定义自定义指标:一个名为 "app_requests_total" 的 Counter
# 描述:监控应用程序的总请求次数
APP_REQUESTS_TOTAL = Counter(
'app_requests_total', # 指标名称
'Total number of requests processed by the application', # 指标描述
['endpoint'] # 标签(可选),用于区分不同端点
)
def process_request(endpoint):
"""模拟处理请求的函数,并更新指标"""
# 业务逻辑:这里简单模拟请求处理
print(f"Processing request for endpoint: {endpoint}")
time.sleep(0.1) # 模拟处理延迟
# 更新指标:每次请求增加 1,并添加标签
APP_REQUESTS_TOTAL.labels(endpoint=endpoint).inc()
if __name__ == '__main__':
# 启动 HTTP 服务器在端口 8000,暴露指标
start_http_server(8000)
print("Exporter started at http://localhost:8000")
# 模拟应用程序运行:持续处理请求
try:
while True:
# 调用处理函数,模拟不同端点的请求
process_request('/api/v1')
process_request('/api/v2')
time.sleep(5) # 每5秒模拟一次请求
except KeyboardInterrupt:
print("Exporter stopped")
步骤 4: 运行和测试
-
运行 Exporter:
- 在终端执行:
python custom_exporter.py - 输出将显示:
Exporter started at http://localhost:8000
- 在终端执行:
-
访问指标:
- 打开浏览器访问
http://localhost:8000,您将看到暴露的指标页面。 - 指标数据格式类似:
# HELP app_requests_total Total number of requests processed by the application # TYPE app_requests_total counter app_requests_total{endpoint="/api/v1"} 5.0 app_requests_total{endpoint="/api/v2"} 5.0- 这里的值会随着时间增加。
- 打开浏览器访问
-
集成 Prometheus:
- 在 Prometheus 配置文件中(如
prometheus.yml),添加以下 job 来抓取此 Exporter:scrape_configs: - job_name: 'custom_exporter' static_configs: - targets: ['localhost:8000'] - 重启 Prometheus 服务,然后可以在 Prometheus UI 中查询指标,例如
app_requests_total。
- 在 Prometheus 配置文件中(如
步骤 5: 扩展和最佳实践
- 添加更多指标:您可以轻松扩展代码,添加 Gauge 或 Histogram。例如,监控处理时间:
from prometheus_client import Histogram REQUEST_TIME = Histogram('request_processing_seconds', 'Time spent processing request') @REQUEST_TIME.time() def process_request(endpoint): # 函数体... - 标签使用:标签(如
['endpoint'])帮助区分不同维度,但避免过多标签以防止性能问题。 - 错误处理:在实际应用中,添加异常处理来确保 Exporter 稳定运行。
- 性能优化:对于高并发场景,使用异步库如
aiohttp配合prometheus_client。
总结
通过以上步骤,您已成功创建了一个 Python 自定义 Prometheus Exporter。核心是使用 prometheus_client 库定义指标,并在应用程序逻辑中更新它们。这个示例监控请求次数,但您可以根据需求扩展(如监控错误率或资源使用)。Prometheus 会自动抓取这些指标,用于告警或可视化(如与 Grafana 集成)。如果您遇到问题,请参考 prometheus_client 官方文档 获取更多示例。
更多推荐


所有评论(0)