開源監控系統 Prometheus 集成了跟蹤多種型別的時間序列資料,但如果沒有整合你想要的資料,那麼很容易構建一個。一個經常使用的例子使用雲端提供商的自定義整合,它使用提供商的 API 抓取特定的指標。但是,在這個例子中,我們將與最大雲端提供商整合:地球。
幸運的是,美國政府已經測量了天氣併為整合提供了一個簡單的 API。獲取紅帽總部下一個小時的天氣預報很簡單。
-
import requests -
HOURLY_RED_HAT = "" -
def get_temperature(): -
result = requests.get(HOURLY_RED_HAT) -
return result.json()["properties"]["periods"][0]["temperature"]
現在我們已經完成了與地球的整合,現在是確保 Prometheus 能夠理解我們想要內容的時候了。我們可以使用 Prometheus Python 庫中的 gauge 建立一個註冊項:紅帽總部的溫度。
-
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 收刮(scrape)它。
我們可以使用 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)伺服器執行。例如,假設我們將程式碼放在 earth.py中,我們可以使用 python -m twisted web --wsgi earth.app 來執行它。
或者,如果我們的程式碼連線到 Prometheus 更容易,我們可以定期將其推送到 Prometheus 的推送閘道器。
-
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 是推送閘道器的 URL。它通常以 :9091 結尾。
祝你構建自定義 Prometheus 整合成功,以便跟蹤一切!
知識星球
朋友會在“發現-看一看”看到你“在看”的內容