Google Cloud MonitoringのメトリクスをPythonで取得する


作ってみましたが、若干詰まったので書いておきます。

コード

コード

from datetime import datetime, timedelta
from google.cloud import monitoring_v3

project = "your-project"  # プロジェクト名
project_id = f"projects/{project}"
instance_name = "instance-name"  # インスタンス名

# 今現在から過去1時間分のデータを取得
now = datetime.now()
time_span_hour = 1
start_ts = int((now - timedelta(hours=time_span_hour)).timestamp())
end_ts = int(now.timestamp())


# フィルターには色々設定可能はこちらを参照 https://cloud.google.com/monitoring/api/v3/filters
metric_filter = f'metric.type = "compute.googleapis.com/instance/cpu/utilization" AND metric.labels.instance_name = "{instance_name}"'

metric_interval = monitoring_v3.TimeInterval(start_time={"seconds": start_ts}, end_time={"seconds": end_ts})
metric_cli = monitoring_v3.MetricServiceClient()
res = metric_cli.list_time_series(
    request=monitoring_v3.ListTimeSeriesRequest(
        name=project_id,
        filter=metric_filter,
        interval=metric_interval,
        view=monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
        aggregation=monitoring_v3.Aggregation(
            alignment_period={"seconds": 300},
            per_series_aligner=monitoring_v3.Aggregation.Aligner.ALIGN_MAX,
        ),
    )
)

for r in res:
    header = f"{r.resource.type} - {r.metric.labels['instance_name']} - {r.metric.type}"
    print(header)
    print("----------------")
    for p in r.points:
        print(f"{p.interval.start_time} : {p.value.double_value}")

出力例

gce_instance - instance-name - compute.googleapis.com/instance/cpu/utilization
----------------
2022-03-22 10:32:27+00:00 : 0.017728691561633998
2022-03-22 10:27:27+00:00 : 0.01778202000300553
2022-03-22 10:22:27+00:00 : 0.018050090768349493
2022-03-22 10:17:27+00:00 : 0.01823367738704557
2022-03-22 10:12:27+00:00 : 0.01796084328830716
2022-03-22 10:07:27+00:00 : 0.020671517363830577
2022-03-22 10:02:27+00:00 : 0.018054658292775607
2022-03-22 09:57:27+00:00 : 0.01777473582532707
2022-03-22 09:52:27+00:00 : 0.017657926236356994
2022-03-22 09:47:27+00:00 : 0.017721036677447916
2022-03-22 09:42:27+00:00 : 0.020249340092521113
2022-03-22 09:37:27+00:00 : 0.0206812247338424

参考