读取指标数据

本页面介绍如何使用 Monitoring API 中的 timeSeries.list 方法读取指标数据(也称为时间序列数据)。您可按多种方式使用此方法:

  • 为了在不编写任何代码的情况下运行 list 方法,本页面上的协议标签页中的示例使用基于表单的 API Explorer。(如需详细了解此工具,请参阅 API Explorer。)

  • 要了解如何通过选定的编程语言使用 list 方法,请参阅本页面的可运行代码示例。

  • 要浏览时间序列数据并查看利用这些数据绘制的图表,请在 Google Cloud Platform Console 的 Stackdriver Monitoring 部分中查看资源 > Metrics Explorer。Metrics Explorer 会为您调用 API 方法。

    转到 Metrics Explorer 页面

如需了解指标和时间序列,请参阅指标、时间序列和资源

概览

每次调用 timeSeries.list 方法都会从单一指标类型返回任意数量的时间序列。例如,如果您正在使用 Google Compute Engine,那么对于每个虚拟机实例,compute.googleapis.com/instance/cpu/usage_time 指标类型都有单独的时间序列。

您通过提供以下信息来指定所需的时间序列数据:

  • 指定指标类型的过滤条件表达式。或者,过滤器通过指定生成时间序列的资源或指定时间序列中特定标签的值,选择指标的部分时间序列。
  • 限制返回多少数据的时间间隔。
  • (可选)关于如何合并多个时间序列以生成数据聚合摘要的规范。如需了解详情,请参阅聚合数据中的一些示例。

时间序列过滤条件

通过将时间序列过滤条件传递给 list 方法,可指定要检索的时间序列。以下是常见的过滤条件组成成分:

  • 过滤条件必须指定单个指标类型。例如:

    metric.type = "compute.googleapis.com/instance/cpu/usage_time"
    

    要检索自定义指标,请将过滤条件中的 metric.type 前缀更改为 custom.googleapis.com 或另一个可能使用的前缀(常用的是 external.googleapis.com)。

  • 过滤条件可为指标的维度标签指定值。指标类型决定了存在哪些标签。例如:

    (metric.label.instance_name = "your-instance-id" OR
      metric.label.instance_name = "your-other-instance-id")
    

    请注意,虽然实际指标对象使用 labels 作为键,但 label 是正确的。

  • 过滤条件可以将时间序列限制为包含特定受监控的资源类型的时间序列:

    resource.type = "gae_app"
    

过滤条件组成成分可合并到单个时间序列过滤条件中,如下所示:

metric.type = "compute.googleapis.com/instance/cpu/usage_time"
AND (metric.label.instance_name = "your-instance-id" OR
  metric.label.instance_name = "your-other-instance-id")

如果您没有为所有指标标签指定值,则 list 方法会为未指定标签中的每个值组合返回时间序列。该方法仅返回包含数据的时间序列。

时间间隔

调用 timeSeries.list 方法时,您必须指定 interval.startTimeinterval.endTime。所产生的时间段包含结束时间,但不包含开始时间,除非二者相同。这可能有点让人迷惑不解。例如,考虑以下 (start, end] 间隔示例:

(T, T+1]
该间隔不包含 T。
(T-1, T]
该间隔包含 T。
(T, T]
这种情况较为特殊,也不常见:该间隔仅包含时间 T。如果您省略开始时间,这就是您获得的时间间隔。

时间间隔中的值

开始时间和结束时间必须指定为 RFC 3339 格式的字符串。例如:

2018-05-11T12:34:56+04:00
2018-05-11T12:34:56.992Z

Linux 上的 date -Iseconds 命令对生成时间戳很有用。

时间间隔中的范围

时间间隔由开始时间和结束时间指定,但 API 并不强制要求指定开始时间。开始时间若未指定,则默认与结束时间相同。这么做仅符合测量时间点的 GAUGE 指标的语义规则。

如果您的指标是 CUMULATIVEDELTA,那么该方法将测量累积值或随时间的变化。对于“随时间的变化”指标,必须同时提供间隔的开始时间和结束时间,并且开始时间必须早于结束时间。

如需了解详情,请参阅指标的种类

基本列表操作

timeSeries.list 方法可用于返回简单的原始数据,也可用于返回已经过复杂处理的数据。本部分列出了一些基本用例。

示例:列出可用的时间序列

此示例显示如何仅列出与过滤条件匹配的时间序列的名称和说明,而不是返回所有可用数据:

协议

下面是 timeSeries.list 的示例参数:

  • nameprojects/[PROJECT_ID]
  • filtermetric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time2018-05-11T00:00:00Z
  • interval.end_time2018-05-11T00:20:00Z
  • fieldstimeSeries.metric

试试看!

点击执行按钮之前,将 [PROJECT_ID] 更改为您的项目 ID。

该示例输出显示了两个不同虚拟机实例的时间序列:

{
  "timeSeries": [
    {
      "metric": {
        "labels": {
          "instance_name": "your-first-instance"
        },
        "type": "compute.googleapis.com/instance/cpu/utilization"
      },
    },
    {
      "metric": {
        "labels": {
          "instance_name": "your-second-instance"
        },
        "type": "compute.googleapis.com/instance/cpu/utilization"
      },
    }
  ]
}

C#

public static object ReadTimeSeriesFields(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    Console.WriteLine($"metricType{ metricType}");
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
        View = ListTimeSeriesRequest.Types.TimeSeriesView.Headers,
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.Write("Found data points for the following instances:");
    foreach (var item in response)
    {
        Console.WriteLine(JObject.Parse($"{item}").ToString());
    }
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

// readTimeSeriesFields reads the last 20 minutes of the given metric, aligns
// everything on 10 minute intervals, and combines values from different
// instances.
func readTimeSeriesFields(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %v", err)
	}
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		View: monitoringpb.ListTimeSeriesRequest_HEADERS,
	}
	fmt.Fprintln(w, "Found data points for the following instances:")
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %v", err)
		}
		fmt.Fprintf(w, "\t%v\n", resp.GetMetric().GetLabels()["instance_name"])
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval = TimeInterval.newBuilder()
    .setStartTime(Timestamps.fromMillis(startMillis))
    .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
    .build();

ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
    .setName(name.toString())
    .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
    .setInterval(interval)
    .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

ListTimeSeriesRequest request = requestBuilder.build();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

System.out.println("Got timeseries headers: ");
for (TimeSeries ts : response.iterateAll()) {
  System.out.println(ts);
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  name: client.projectPath(projectId),
  filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
  interval: {
    startTime: {
      // Limit results to the last 20 minutes
      seconds: Date.now() / 1000 - 60 * 20,
    },
    endTime: {
      seconds: Date.now() / 1000,
    },
  },
  // Don't return time series data, instead just return information about
  // the metrics that match the filter
  view: 'HEADERS',
};

// Writes time series data
const [timeSeries] = await client.listTimeSeries(request);
console.log('Found data points for the following instances:');
timeSeries.forEach(data => {
  console.log(data.metric.labels.instance_name);
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_fields($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_fields($projectId, $minutesAgo = 20)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = $metrics->projectName($projectId);
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $view = ListTimeSeriesRequest_TimeSeriesView::HEADERS;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view);

    printf('Found data points for the following instances:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        printf($timeSeries->getMetric()->getLabels()['instance_name'] . PHP_EOL);
    }
}

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 300)
interval.start_time.nanos = interval.end_time.nanos
results = client.list_time_series(
    project_name,
    'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
    interval,
    monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.HEADERS)
for result in results:
    print(result)

Ruby

client = Google::Cloud::Monitoring::Metric.new
project_name = Google::Cloud::Monitoring::V3::MetricServiceClient.project_path project_id

interval = Google::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.usec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 300, nanos: now.usec

results = client.list_time_series(
  project_name,
  'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
  interval,
  Google::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::HEADERS
)
results.each do |result|
  p result
end

如果遇到困难,请参阅 API 调用问题排查

示例:获取时间序列数据

此示例返回过去 20 分钟内来自 Compute Engine 实例的 timeSeries.list 请求的所有可用信息(包括指标数据)。

协议

协议示例进一步对输出进行限制,以使返回的数据在响应框中更易于管理。此示例使用不同的字段值:

  • filter 值现在将时间序列限制为单个虚拟机实例。
  • fields 值现在仅指定测量结果的时间和值。

这些值将限制结果中返回的时间序列数据量。

下面是 timeSeries.list 的示例参数:

  • nameprojects/[PROJECT_ID]
  • filtermetric.type = "compute.googleapis.com/instance/cpu/utilization" AND metric.label.instance_name = "[YOUR_INSTANCE_NAME]"
  • interval.start_time2018-05-11T00:00:00Z
  • interval.end_time2018-05-11T00:20:00Z
  • fieldstimeSeries.points.interval.endTime,timeSeries.points.value

试试看!

点击执行按钮之前,将 [PROJECT_ID][YOUR_INSTANCE_NAME] 更改为项目中的值,并将结束时间设置为最近某个时间,将开始时间设置为早于结束时间 20 分钟的时间。

请求将返回如下结果:

{
 "timeSeries": [
  {
   "points": [
    {
     "interval": {
      "endTime": "2018-05-T00:19:01Z"
     },
     "value": {
      "doubleValue": 0.06763074536575005
     }
    },
    {
     "interval": {
      "endTime": "2018-05-11T00:18:01Z"
     },
     "value": {
      "doubleValue": 0.06886174467702706
     }
    },
    ...
    {
     "interval": {
      "endTime": "2018-05-11T00:17:01Z"
     },
     "value": {
      "doubleValue": 0.06929610064253211
     }
    }
   ]
  }
 ]
}

C#

public static object ReadTimeSeriesData(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
        View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    foreach (TimeSeries item in response)
    {
        Console.WriteLine(JObject.Parse($"{item}").ToString());
    }
    return 0;
}

Go

// readTimeSeriesValue reads the TimeSeries for the value specified by metric type in a time window from the last 5 minutes.
func readTimeSeriesValue(projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	startTime := time.Now().UTC().Add(time.Minute * -5).Unix()
	endTime := time.Now().UTC().Unix()

	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: fmt.Sprintf("metric.type=\"%s\"", metricType),
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{Seconds: startTime},
			EndTime:   &timestamp.Timestamp{Seconds: endTime},
		},
	}
	iter := c.ListTimeSeries(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value, %v ", err)
		}
		log.Printf("%+v\n", resp)
	}

	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval = TimeInterval.newBuilder()
    .setStartTime(Timestamps.fromMillis(startMillis))
    .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
    .build();

ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
    .setName(name.toString())
    .setFilter(filter)
    .setInterval(interval);

ListTimeSeriesRequest request = requestBuilder.build();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

System.out.println("Got timeseries: ");
for (TimeSeries ts : response.iterateAll()) {
  System.out.println(ts);
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

const request = {
  name: client.projectPath(projectId),
  filter: filter,
  interval: {
    startTime: {
      // Limit results to the last 20 minutes
      seconds: Date.now() / 1000 - 60 * 20,
    },
    endTime: {
      seconds: Date.now() / 1000,
    },
  },
};

// Writes time series data
const [timeSeries] = await client.listTimeSeries(request);
timeSeries.forEach(data => {
  console.log(`${data.metric.labels.instance_name}:`);
  data.points.forEach(point => {
    console.log(JSON.stringify(point.value));
  });
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_simple($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_simple($projectId, $minutesAgo = 20)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = $metrics->projectName($projectId);
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    // Limit results to the last 20 minutes
    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $view = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view);

    printf('CPU utilization:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        $instanceName = $timeSeries->getMetric()->getLabels()['instance_name'];
        printf($instanceName . ':' . PHP_EOL);
        foreach ($timeSeries->getPoints() as $point) {
            printf('  ' . $point->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 300)
interval.start_time.nanos = interval.end_time.nanos
results = client.list_time_series(
    project_name,
    'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
    interval,
    monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL)
for result in results:
    print(result)

Ruby

client = Google::Cloud::Monitoring::Metric.new
project_name = Google::Cloud::Monitoring::V3::MetricServiceClient.project_path project_id

interval = Google::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.usec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 300, nanos: now.usec

results = client.list_time_series(
  project_name,
  'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
  interval,
  Google::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL
)
results.each do |result|
  p result
end

返回的数据包括 20 分钟内每个时间序列中的 20 个数据点,因为 Compute Engine 指标的收集频率是每分钟。如需了解详情,请参阅指标数据的延迟时间。API 以反向时间顺序返回每个时间序列中的数据点,此类点排序没有覆盖。

如果遇到困难,请参阅 API 调用问题排查

聚合数据

timeSeries.list 方法可对返回的时间序列数据执行统计聚合和缩减。以下部分展示了两个示例。如需了解更多选项,请参阅该方法的文档。

示例:校准时间序列

此示例将各个时间序列中的 20 个独立的利用率测量结果缩减为两个测量结果:20 分钟间隔中两个 10 分钟时间段的平均利用率。来自各个时间序列的数据首先校准到 10 分钟(600 秒)时间段,然后对每个 10 分钟时间段中的值进行均值计算。

该示例将各个时间序列的 20 个测量结果按时间序列分成两组。此操作有两个优势:可以缩减数据,还可以将所有时间序列中的数据校准至准确的 10 分钟间隔。然后,您可以进一步处理数据。

协议

下面是 timeSeries.list 的示例参数:

  • nameprojects/[PROJECT_ID]
  • aggregation.alignmentPeriod600s
  • aggregation.perSeriesAlignerALIGN_MEAN
  • filtermetric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time2018-05-11T00:00:00Z
  • interval.end_time2018-05-11T00:20:00Z
  • fieldstimeSeries.metric,timeSeries.points

上一个示例中显示的针对单个实例的过滤条件将被删除:此查询返回的数据少得多,因此不需要将其限制为一个虚拟机实例。

试试看!

点击执行按钮之前,将 [PROJECT_ID] 更改为项目的 ID,并将结束时间调整为最近某个时间,将开始时间调整为早于结束时间 20 分钟的时间。

以下示例结果为三个虚拟机实例中的每一个提供一个时间序列。每个时间序列具有两个数据点,即 10 分钟校准时间段的平均利用率:

{
 "timeSeries": [
  {
   "metric": {
    "labels": {"instance_name": "your-first-instance"},
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.06688481346044381 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": {"doubleValue": 0.06786652821310177 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-second-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.04144239874207415 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": { "doubleValue": 0.04045793689050091 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-third-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.029650046587339607 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": { "doubleValue": 0.03053874224715402 }
    }
   ]
  }
 ]
}

C#

public static object ReadTimeSeriesAggregate(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Aggregate results per matching instance
    Aggregation aggregation = new Aggregation();
    Duration alignmentPeriod = new Duration();
    alignmentPeriod.Seconds = 600;
    aggregation.AlignmentPeriod = alignmentPeriod;
    aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
    // Add the aggregation to the request.
    request.Aggregation = aggregation;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.WriteLine($"{projectId} CPU utilization:");
    foreach (var item in response)
    {
        var points = item.Points;
        var labels = item.Metric.Labels;
        Console.WriteLine($"{labels.Values.FirstOrDefault()}");
        if (points.Count > 0)
        {
            Console.WriteLine($"  Now: {points[0].Value.DoubleValue}");
        }
        if (points.Count > 1)
        {
            Console.WriteLine($"  10 min ago: {points[1].Value.DoubleValue}");
        }
    }
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"github.com/golang/protobuf/ptypes/duration"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

// readTimeSeriesAlign reads the last 20 minutes of the given metric and aligns
// everything on 10 minute intervals.
func readTimeSeriesAlign(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %v", err)
	}
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		Aggregation: &monitoringpb.Aggregation{
			PerSeriesAligner: monitoringpb.Aggregation_ALIGN_MEAN,
			AlignmentPeriod: &duration.Duration{
				Seconds: 600,
			},
		},
	}
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %v", err)
		}
		fmt.Fprintln(w, resp.GetMetric().GetLabels()["instance_name"])
		fmt.Fprintf(w, "\tNow: %.4f\n", resp.GetPoints()[0].GetValue().GetDoubleValue())
		if len(resp.GetPoints()) > 1 {
			fmt.Fprintf(w, "\t10 minutes ago: %.4f\n", resp.GetPoints()[1].GetValue().GetDoubleValue())
		}
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval = TimeInterval.newBuilder()
    .setStartTime(Timestamps.fromMillis(startMillis))
    .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
    .build();

Aggregation aggregation = Aggregation.newBuilder()
    .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
    .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
    .build();

ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
    .setName(name.toString())
    .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
    .setInterval(interval)
    .setAggregation(aggregation);

ListTimeSeriesRequest request = requestBuilder.build();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

System.out.println("Got timeseries: ");
for (TimeSeries ts : response.iterateAll()) {
  System.out.println(ts);
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  name: client.projectPath(projectId),
  filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
  interval: {
    startTime: {
      // Limit results to the last 20 minutes
      seconds: Date.now() / 1000 - 60 * 20,
    },
    endTime: {
      seconds: Date.now() / 1000,
    },
  },
  // Aggregate results per matching instance
  aggregation: {
    alignmentPeriod: {
      seconds: 600,
    },
    perSeriesAligner: 'ALIGN_MEAN',
  },
};

// Writes time series data
const [timeSeries] = await client.listTimeSeries(request);
console.log('CPU utilization:');
timeSeries.forEach(data => {
  console.log(data.metric.labels.instance_name);
  console.log(`  Now: ${data.points[0].value.doubleValue}`);
  console.log(`  10 min ago: ${data.points[1].value.doubleValue}`);
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\Aggregation_Aligner;
use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_align($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_align($projectId, $minutesAgo = 20)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = $metrics->projectName($projectId);
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $alignmentPeriod = new Duration();
    $alignmentPeriod->setSeconds(600);
    $aggregation = new Aggregation();
    $aggregation->setAlignmentPeriod($alignmentPeriod);
    $aggregation->setPerSeriesAligner(Aggregation_Aligner::ALIGN_MEAN);

    $view = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view,
        ['aggregation' => $aggregation]);

    printf('CPU utilization:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        printf($timeSeries->getMetric()->getLabels()['instance_name'] . PHP_EOL);
        printf('  Now: ');
        printf($timeSeries->getPoints()[0]->getValue()->getDoubleValue() . PHP_EOL);
        if (count($timeSeries->getPoints()) > 1) {
            printf('  10 minutes ago: ');
            printf($timeSeries->getPoints()[1]->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 3600)
interval.start_time.nanos = interval.end_time.nanos
aggregation = monitoring_v3.types.Aggregation()
aggregation.alignment_period.seconds = 300  # 5 minutes
aggregation.per_series_aligner = (
    monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)

results = client.list_time_series(
    project_name,
    'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
    interval,
    monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL,
    aggregation)
for result in results:
    print(result)

Ruby

client = Google::Cloud::Monitoring::Metric.new
project_name = Google::Cloud::Monitoring::V3::MetricServiceClient.project_path project_id

interval = Google::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.usec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 300, nanos: now.usec

aggregation = Google::Monitoring::V3::Aggregation.new(
  alignment_period:   { seconds: 300 },
  per_series_aligner: Google::Monitoring::V3::Aggregation::Aligner::ALIGN_MEAN
)

results = client.list_time_series(
  project_name,
  'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
  interval,
  Google::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL,
  aggregation: aggregation
)
results.each do |result|
  p result
end

如果遇到困难,请参阅 API 调用问题排查

示例:跨多个时间序列进行缩减

此示例进一步扩展了上一示例,将三个虚拟机实例中的已校准时间序列合并为单个时间序列,以测量所有实例的平均利用率。

协议

下面是 timeSeries.list 的示例参数,与上一个示例的唯一区别在于包含 aggregation.crossSeriesReducer

  • nameprojects/[PROJECT_ID]
  • aggregation.alignmentPeriod600s
  • aggregation.crossSeriesReducerREDUCE_MEAN
  • aggregation.perSeriesAlignerALIGN_MEAN
  • filtermetric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time2018-05-11T00:00:00Z
  • interval.end_time2018-05-11T00:20:00Z
  • fieldstimeSeries.metric,timeSeries.points

试试看!

点击执行按钮之前,将 [PROJECT_ID] 更改为项目的 ID,并将结束时间调整为最近某个时间,将开始时间调整为早于结束时间 20 分钟的时间。

以下示例结果只有一个时间序列和两个数据点。每个数据点是相应时间段内三个虚拟机实例的平均利用率:

{
 "timeSeries": [
  {
   "metric": {
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": {
      "doubleValue": 0.045992419596619184
     }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": {
      "doubleValue": 0.04628773578358556
     }
    }
   ]
  }
 ]
}

C#

public static object ReadTimeSeriesReduce(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Aggregate results per matching instance.
    Aggregation aggregation = new Aggregation();
    Duration alignmentPeriod = new Duration();
    alignmentPeriod.Seconds = 600;
    aggregation.AlignmentPeriod = alignmentPeriod;
    aggregation.CrossSeriesReducer = Aggregation.Types.Reducer.ReduceMean;
    aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
    // Add the aggregation to the request.
    request.Aggregation = aggregation;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.WriteLine("CPU utilization:");
    foreach (var item in response)
    {
        var points = item.Points;
        Console.WriteLine("Average CPU utilization across all GCE instances:");
        Console.WriteLine($"  Last 10 min: {points[0].Value.DoubleValue}");
        Console.WriteLine($"  Last 10-20 min ago: {points[1].Value.DoubleValue}");
    }
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"github.com/golang/protobuf/ptypes/duration"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

// readTimeSeriesReduce reads the last 20 minutes of the given metric, aligns
// everything on 10 minute intervals, and combines values from different
// instances.
func readTimeSeriesReduce(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %v", err)
	}
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		Aggregation: &monitoringpb.Aggregation{
			CrossSeriesReducer: monitoringpb.Aggregation_REDUCE_MEAN,
			PerSeriesAligner:   monitoringpb.Aggregation_ALIGN_MEAN,
			AlignmentPeriod: &duration.Duration{
				Seconds: 600,
			},
		},
	}
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %v", err)
		}
		fmt.Fprintln(w, "Average CPU utilization across all GCE instances:")
		fmt.Fprintf(w, "\tNow: %.4f\n", resp.GetPoints()[0].GetValue().GetDoubleValue())
		fmt.Fprintf(w, "\t10 minutes ago: %.4f\n", resp.GetPoints()[1].GetValue().GetDoubleValue())
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval = TimeInterval.newBuilder()
    .setStartTime(Timestamps.fromMillis(startMillis))
    .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
    .build();

Aggregation aggregation = Aggregation.newBuilder()
    .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
    .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
    .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
    .build();

ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
    .setName(name.toString())
    .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
    .setInterval(interval)
    .setAggregation(aggregation);

ListTimeSeriesRequest request = requestBuilder.build();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

System.out.println("Got timeseries: ");
for (TimeSeries ts : response.iterateAll()) {
  System.out.println(ts);
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  name: client.projectPath(projectId),
  filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
  interval: {
    startTime: {
      // Limit results to the last 20 minutes
      seconds: Date.now() / 1000 - 60 * 20,
    },
    endTime: {
      seconds: Date.now() / 1000,
    },
  },
  // Aggregate results per matching instance
  aggregation: {
    alignmentPeriod: {
      seconds: 600,
    },
    crossSeriesReducer: 'REDUCE_MEAN',
    perSeriesAligner: 'ALIGN_MEAN',
  },
};

// Writes time series data
const [result] = await client.listTimeSeries(request);
if (result.length === 0) {
  console.log('No data');
  return;
}
const reductions = result[0].points;

console.log('Average CPU utilization across all GCE instances:');
console.log(`  Last 10 min: ${reductions[0].value.doubleValue}`);
console.log(`  10-20 min ago: ${reductions[0].value.doubleValue}`);

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\Aggregation_Aligner;
use Google\Cloud\Monitoring\V3\Aggregation_Reducer;
use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_reduce($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_reduce($projectId, $minutesAgo = 20)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = $metrics->projectName($projectId);
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $alignmentPeriod = new Duration();
    $alignmentPeriod->setSeconds(600);
    $aggregation = new Aggregation();
    $aggregation->setAlignmentPeriod($alignmentPeriod);
    $aggregation->setCrossSeriesReducer(Aggregation_Reducer::REDUCE_MEAN);
    $aggregation->setPerSeriesAligner(Aggregation_Aligner::ALIGN_MEAN);

    $view = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view,
        ['aggregation' => $aggregation]);

    printf('Average CPU utilization across all GCE instances:' . PHP_EOL);
    if ($timeSeries = $result->iterateAllElements()->current()) {
        $reductions = $timeSeries->getPoints();
        printf('  Last 10 minutes: ');
        printf($reductions[0]->getValue()->getDoubleValue() . PHP_EOL);
        if (count($reductions) > 1) {
            printf('  10-20 minutes ago: ');
            printf($reductions[1]->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 3600)
interval.start_time.nanos = interval.end_time.nanos
aggregation = monitoring_v3.types.Aggregation()
aggregation.alignment_period.seconds = 300  # 5 minutes
aggregation.per_series_aligner = (
    monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)
aggregation.cross_series_reducer = (
    monitoring_v3.enums.Aggregation.Reducer.REDUCE_MEAN)
aggregation.group_by_fields.append('resource.zone')

results = client.list_time_series(
    project_name,
    'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
    interval,
    monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL,
    aggregation)
for result in results:
    print(result)

Ruby

client = Google::Cloud::Monitoring::Metric.new
project_name = Google::Cloud::Monitoring::V3::MetricServiceClient.project_path project_id

interval = Google::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.usec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 300, nanos: now.usec

aggregation = Google::Monitoring::V3::Aggregation.new(
  alignment_period:     { seconds: 300 },
  per_series_aligner:   Google::Monitoring::V3::Aggregation::Aligner::ALIGN_MEAN,
  cross_series_reducer: Google::Monitoring::V3::Aggregation::Reducer::REDUCE_MEAN,
  group_by_fields:      ["resource.zone"]
)

results = client.list_time_series(
  project_name,
  'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
  interval,
  Google::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL,
  aggregation: aggregation
)
results.each do |result|
  p result
end

如果遇到困难,请参阅 API 调用问题排查

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Stackdriver Monitoring
需要帮助?请访问我们的支持页面