开源监控系统 Prometheus 具有集成功能,可以跟踪多种类型的时间序列数据,但是如果您想要一个尚不存在的集成,则很容易构建一个。 一个常用的例子是与云提供商的自定义集成,该集成使用提供商的 API 来获取特定指标。 但是,在此示例中,我们将与最大的云提供商:地球集成。
幸运的是,美国政府已经测量了天气,并提供了一个易于集成的 API。 获取 Red Hat 总部接下来一小时的天气预报很简单。
import requests
HOURLY_RED_HAT = "https://api.weather.gov/gridpoints/RAH/73,57/forecast/hourly"
def get_temperature():
result = requests.get(HOURLY_RED_HAT)
return result.json()["properties"]["periods"][0]["temperature"]
既然我们与地球的集成已经完成,就该确保 Prometheus 可以理解我们在说什么了。 我们可以使用 Prometheus Python 库 创建一个注册表,其中包含一个计量器:Red Hat 总部的温度。
from prometheus_client import CollectorRegistry, Gauge
def prometheus_temperature(num):
registry = CollectorRegistry()
g = Gauge("red_hat_temp", "Temperature at Red Hat HQ", registry=registry)
g.set(num)
return registry
最后,我们需要以某种方式将其连接到 Prometheus。 这在某种程度上取决于 Prometheus 的网络拓扑:是 Prometheus 与我们的服务通信更容易,还是反过来更容易。
如果可能,通常建议使用第一种情况,因此我们需要构建一个 Web 服务器来公开注册表,然后配置 Prometheus 来抓取它。
我们可以使用 Pyramid 构建一个简单的 Web 服务器。
from pyramid.config import Configurator
from pyramid.response import Response
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST
def metrics_web(request):
registry = prometheus_temperature(get_temperature())
return Response(generate_latest(registry),
content_type=CONTENT_TYPE_LATEST)
config = Configurator()
config.add_route('metrics', '/metrics')
config.add_view(metrics_web, route_name='metrics')
app = config.make_wsgi_app()
这可以使用任何 Web 服务器网关接口 (WSGI) 服务器运行。 例如,我们可以使用 python -m twisted web --wsgi earth.app 运行它,假设我们将代码放在 earth.py 中。
或者,如果我们的代码更容易连接到 Prometheus,我们可以定期将其推送到 Prometheus 的 Push gateway。
import time
from prometheus_client import push_to_gateway
def push_temperature(url):
while True:
registry = prometheus_temperature(get_temperature())
push_to_gateway(url, "temperature collector", registry)
time.sleep(60*60)
该 URL 是 Push gateway 的 URL;它通常以 :9091 结尾。
祝您成功构建自己的自定义 Prometheus 集成,以便您可以跟踪所有内容!
1 条评论