0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PrometheusのメトリクスをAPI経由で取得して時系列でCSV保存する

Last updated at Posted at 2025-11-02

はじめに

Prometheusで収集したメトリクスは,Grafanaをもちいるとダッシュボード上で可視化でき,非常に便利です.しかし,時には収集したメトリクスを数値データとして保存したい場合もあります.その場合には,PrometheusのHTTP APIを使用する方法が有効です.

この記事ではPrometheusAPIをもちいてPrometheusで収集したメトリクスを取得し,CSV形式で保存する方法について説明します.

環境

  • Ubuntu:24.04.3
  • Python:3.12.3
    • requests:2.32.5
  • kubernetes:v1.30.6+k3s1
  • Prometheus:2.53.1

構成は以下の図のようになっています.
監視対象のアプリケーションはESXi1上にあるkubernetes cluster上に構成されており,PrometheusはBlackbox exporterを通じてHTTPの監視をしています.
今回作業する仮想マシンはESXi2上にあります.ここからPrometheusのAPIを利用してメトリクスを取得し,CSV 形式で出力するスクリプトを作成します.
image.png

Prometheus APIの概要

PrometheusはHTTP APIを通じてメトリクスを取得します.
メトリクスを取得する時に使用することなるエンドポイントは以下の2つです.

/api/v1/query :単一地点でのメトリクスを取得できる
/api/v1/query_range :一定期間のメトリクスを取得できる

この記事では/api/v1/query_rangeを使用します.

APIをcurlで試してみる

まず,curlコマンドを使ってPrometheusAPI経由でデータを取得してみます.

例として以下に私が実行したコマンドとその結果を載せます.この例ではPrometheusが稼働しているサーバ(monitoring-master-ml:30900)に対して,
probe_http_status_code メトリクスを指定し,
2025-11-01T08:00:00Z から 2025-11-01T08:01:00Z の1分間を,15秒間隔(step=15s)で取得しました.

c0a22069@c0a22069-log-collector:~$ curl "http://monitoring-master-ml:30900/api/v1/query_range?query=probe_http_status_code%7Bjob%3D%22External-Doktor-http-page%22%2Cinstance%3D%22http%3A%2F%2F192.168.201.8%2F%22%7D&start=2025-11-01T08:00:00Z&end=2025-11-01T08:01:00Z&step=15s"{"status":"success","data":{"resultType":"matrix","result":[{"metric":{"__name__":"probe_http_status_code","instance":"http://192.168.201.8/","job":"External-Doktor-http-page"},"values":[[1761984000,"200"],[1761984015,"200"],[1761984030,"200"],[1761984045,"200"],[1761984060,"200"]]}]}}c0a22069@c0a22069-log-collector:~$

PythonでPrometheusAPIを呼び出してCSVに保存する

先ほど確認したAPIリクエストをPythonスクリプトから自動的に実行し,CSV形式で保存します.

仮想環境を使用する場合は以下のコマンドを実行します.
コマンドと実行結果

c0a22069@c0a22069-log-collector:~/prometheus_export$ python3 -m venv test
c0a22069@c0a22069-log-collector:~/prometheus_export_pub$ 

仮想環境をアクティベートします.

c0a22069@c0a22069-log-collector:~/prometheus_export$ source test/bin/activate
(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ 

requestsをインストールします.既にインストール済みなので出力が異なりますが,以下のコマンドを実行することでインストールできます.

(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ pip3 install requests
Requirement already satisfied: requests in ./test/lib/python3.12/site-packages (2.32.5)
Requirement already satisfied: charset_normalizer<4,>=2 in ./test/lib/python3.12/site-packages (from requests) (3.4.4)
Requirement already satisfied: idna<4,>=2.5 in ./test/lib/python3.12/site-packages (from requests) (3.11)
Requirement already satisfied: urllib3<3,>=1.21.1 in ./test/lib/python3.12/site-packages (from requests) (2.5.0)
Requirement already satisfied: certifi>=2017.4.17 in ./test/lib/python3.12/site-packages (from requests) (2025.10.5)
(test) c0a22069@c0a22069-log-collector:~/prometheus_export$

例として,以下に先ほどのコマンドをもちいて取得した結果をCSVに保存するスクリプト載せます.

import requests
import csv
from datetime import datetime

# === Prometheus API設定 ===
PROM_URL = "http://monitoring-master-ml:30900/api/v1/query_range"
JOB_NAME = "External-Doktor-http-page"
INSTANCE = "http://192.168.201.8/"
STEP = "15s"

# === 取得する期間(UTC) ===
START = "2025-11-01T08:00:00Z"
END = "2025-11-01T08:01:00Z"

# === 出力先 ===
OUTPUT_PATH = "./status_code_metrics_single.csv"

# === APIパラメータ設定 ===
query = f'probe_http_status_code{{job="{JOB_NAME}", instance="{INSTANCE}"}}'
params = {
    "query": query,
    "start": START,
    "end": END,
    "step": STEP
}

# === APIリクエスト ===
response = requests.get(PROM_URL, params=params)
data = response.json()

results = data.get("data", {}).get("result", [])

# === CSVに書き出し ===
with open(OUTPUT_PATH, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["timestamp", "value"])

    for series in results:
        for timestamp, val in series["values"]:
            ts = datetime.utcfromtimestamp(float(timestamp)).strftime("%Y-%m-%d %H:%M:%S")
            writer.writerow([ts, val])

実行方法とその結果

(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ python3 get-met.py
/home/c0a22069/prometheus_export/get-met.py:40: DeprecationWarning: datetime.datetime.utcfromtimestamp() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).
  ts = datetime.utcfromtimestamp(float(timestamp)).strftime("%Y-%m-%d %H:%M:%S")
(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ 

↑の実行によって出力されたCSVファイルの中身

(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ ls
get-met.py  test  test_status_code_metrics.csv
(test) c0a22069@c0a22069-log-collector:~/prometheus_export$ cat test_status_code_metrics.csv 
timestamp,192.168.201.8,192.168.201.9,192.168.201.10,192.168.201.11
2025-11-02 07:50:00,200,200,200,200
2025-11-02 07:50:15,200,200,200,200
2025-11-02 07:50:30,200,200,200,200
2025-11-02 07:50:45,200,200,200,200
(test) c0a22069@c0a22069-log-collector:~/prometheus_export$

終わりに

本記事では,PrometheusのHTTP APIを用いて,メトリクスを指定した期間・間隔で取得し,PythonでCSV形式に保存する方法を紹介しました.
今回の例では1つのターゲットに対して固定期間のデータを取得しましたが,複数ターゲットを処理したり,定期実行に組み込むことも可能です.
また,PrometheusのAPIは他にも多くのエンドポイントが用意されています.用途に応じて活用してみてください.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?