You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python通过API获取GCP API的请求、错误等数据及嵌入图表?

如何用Python获取Google Cloud API的监控指标及嵌入图表?

一、用Python通过API提取监控指标

1. 前置准备

  • 安装Google Cloud监控的Python SDK:
    pip install google-cloud-monitoring
    
  • 完成身份认证:
    • 本地开发:执行gcloud auth application-default login,按提示完成登录
    • 服务器部署:将服务账号密钥文件放在服务器上,设置环境变量export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"

2. 获取API整体的Requests、Errors、Latency数据

以下代码可查询指定API在过去1小时的核心指标:

from google.cloud import monitoring_v3
from google.protobuf.timestamp_pb2 import Timestamp
import datetime

# 初始化客户端
client = monitoring_v3.MetricServiceClient()
# 替换为你的项目ID
PROJECT_ID = "your-project-id"
project_name = f"projects/{PROJECT_ID}"
# 替换为目标API名称,比如storage.googleapis.com
TARGET_API = "your-target-api"

# 设置查询时间范围:过去1小时
end_time = datetime.datetime.now(datetime.timezone.utc)
start_time = end_time - datetime.timedelta(hours=1)

# 转换为监控API要求的Timestamp格式
start_ts = Timestamp()
start_ts.FromDatetime(start_time)
end_ts = Timestamp()
end_ts.FromDatetime(end_time)

# 查询Requests总数
def fetch_requests():
    request_query = monitoring_v3.ListTimeSeriesRequest(
        name=project_name,
        filter=f'metric.type="serviceruntime.googleapis.com/api/request_count" AND resource.type="api" AND resource.label."api_service"="{TARGET_API}"',
        interval=monitoring_v3.TimeInterval(start_time=start_ts, end_time=end_ts),
        view=monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
    )
    for series in client.list_time_series(request_query):
        print("=== Requests 数据 ===")
        for point in series.points:
            print(f"时间: {point.interval.start_time}, 数值: {point.value.int64_value}")

# 查询Errors总数
def fetch_errors():
    error_query = monitoring_v3.ListTimeSeriesRequest(
        name=project_name,
        filter=f'metric.type="serviceruntime.googleapis.com/api/error_count" AND resource.type="api" AND resource.label."api_service"="{TARGET_API}"',
        interval=monitoring_v3.TimeInterval(start_time=start_ts, end_time=end_ts),
        view=monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
    )
    for series in client.list_time_series(error_query):
        print("\n=== Errors 数据 ===")
        for point in series.points:
            print(f"时间: {point.interval.start_time}, 数值: {point.value.int64_value}")

# 查询Latency分位数(p50/p95/p99)
def fetch_latency():
    latency_query = monitoring_v3.ListTimeSeriesRequest(
        name=project_name,
        filter=f'metric.type="serviceruntime.googleapis.com/api/latencies" AND resource.type="api" AND resource.label."api_service"="{TARGET_API}"',
        interval=monitoring_v3.TimeInterval(start_time=start_ts, end_time=end_ts),
        view=monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
    )
    for series in client.list_time_series(latency_query):
        percentile = series.metric.labels["percentile"]
        print(f"\n=== Latency {percentile} 数据 ===")
        for point in series.points:
            print(f"时间: {point.interval.start_time}, 数值: {point.value.double_value} 秒")

# 执行所有查询
fetch_requests()
fetch_errors()
fetch_latency()

3. 获取单个API Method的指标数据

如果要查询特定方法(比如storage.objects.get)的指标,只需在过滤条件中添加metric.label."method"即可,示例代码:

def fetch_method_metrics(method_name):
    # 查询指定Method的Requests
    method_request_query = monitoring_v3.ListTimeSeriesRequest(
        name=project_name,
        filter=f'metric.type="serviceruntime.googleapis.com/api/request_count" AND resource.type="api" AND resource.label."api_service"="{TARGET_API}" AND metric.label."method"="{method_name}"',
        interval=monitoring_v3.TimeInterval(start_time=start_ts, end_time=end_ts),
        view=monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
    )
    for series in client.list_time_series(method_request_query):
        print(f"\n=== Method {method_name} Requests ===")
        for point in series.points:
            print(f"时间: {point.interval.start_time}, 数值: {point.value.int64_value}")

# 调用示例,替换为目标Method名称
fetch_method_metrics("storage.objects.get")

如果要获取该API下所有Method的指标,去掉过滤条件中的metric.label."method",遍历结果时通过series.metric.labels["method"]区分不同方法即可。

二、嵌入API监控图表到其他网站

Google Cloud Console的API详情页图表无法直接通过IFrame嵌入,原因是控制台有严格的身份验证和同源策略限制,浏览器会阻止跨域IFrame加载。

可行的替代方案:

  • 用上面的Python代码获取原始指标数据,然后结合Chart.js、Plotly等前端图表库,在自己的网站上生成自定义监控图表
  • 使用Google Cloud Monitoring的自定义仪表盘功能,创建包含目标API指标的仪表盘,然后通过仪表盘的分享功能生成链接(但用户仍需登录Google Cloud账号才能查看)

内容的提问来源于stack exchange,提问作者GeekGeek4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:27:27