當前位置:
首頁 > 知識 > 使用 Python 和 Prometheus 跟蹤天氣

使用 Python 和 Prometheus 跟蹤天氣

使用 Python 和 Prometheus 跟蹤天氣


創建自定義 Prometheus 集成以跟蹤最大的雲端提供商:地球母親。

-- Moshe Zadka

開源監控系統 Prometheus 集成了跟蹤多種類型的時間序列數據,但如果沒有集成你想要的數據,那麼很容易構建一個。一個經常使用的例子使用雲端提供商的自定義集成,它使用提供商的 API 抓取特定的指標。但是,在這個例子中,我們將與最大雲端提供商集成:地球。

幸運的是,美國政府已經測量了天氣並為集成提供了一個簡單的 API。獲取紅帽總部下一個小時的天氣預報很簡單。

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 庫 中的 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 集成成功,以便跟蹤一切!



via: https://opensource.com/article/19/4/weather-python-prometheus

作者: Moshe Zadka 選題: lujun9972 譯者: geekpi 校對: wxy

本文由 LCTT 原創編譯, Linux中國 榮譽推出

點擊「了解更多」可訪問文內鏈接

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 Linux技術 的精彩文章:

楊鐳訪談:UCloud 的技術價值觀
命令行技巧:分割文件內容

TAG:Linux技術 |