Prometheus 通过暴露 HTTP 端点(通常是 /metrics
)从应用程序抓取指标。这个端点需要返回 Prometheus 可以理解的格式(即 Prometheus Exposition Format)的指标数据。
以下是在应用程序中暴露 Prometheus 指标的基本步骤:
-
添加 Prometheus 客户端库:Prometheus 提供了多种语言的客户端库,包括 Go、Java、Python、Ruby 等。你需要在你的应用程序中添加对应的 Prometheus 客户端库。
-
定义和收集指标:使用 Prometheus 客户端库定义你想要收集的指标,然后在应用程序的适当位置收集这些指标。
-
暴露指标:在应用程序中添加一个 HTTP 端点(通常是
/metrics
),并在这个端点返回你收集的指标。 -
配置 Prometheus 抓取:在 Prometheus 的配置文件中添加一个抓取配置,指向你的应用程序的
/metrics
端点。
以下是一个使用 Python 的 Prometheus 客户端库在 Flask 应用中暴露指标的例子:
from flask import Flask, Response
from prometheus_client import generate_latest, Counter
app = Flask(__name__)
# 定义一个 Counter 指标
requests_total = Counter("requests_total", "Total request count")
@app.route('/')
def hello_world():
# 在每个请求中增加 Counter 的值
requests_total.inc()
return 'Hello, World!'
@app.route('/metrics')
def metrics():
# 在 /metrics 端点返回 Prometheus 指标
return Response(generate_latest(), mimetype='text/plain')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
在这个例子中,每次请求 /
时,requests_total
指标的值会增加。你可以通过访问 /metrics
端点来获取 requests_total
指标的当前值。