讀取指標資料

本頁面說明如何在 Monitoring API 中使用 timeSeries.list 方法讀取指標資料 (也稱為時間序列資料)。您可以透過一些方式使用這個方法:

  • 為了在不編寫任何程式碼的情況下執行 list 方法,本頁面「通訊協定」分頁中的範例使用表單式 API Explorer (如要進一步瞭解這項工具,請參閱 API Explorer)。

  • 如要瞭解如何從所選程式設計語言使用 list 方法,請參閱本頁面的可執行程式碼範例。

  • 如要瀏覽時間序列資料,並查看其相關圖表,請前往 Google Cloud Platform 主控台的「Stackdriver Monitoring」區段,查看「Resources」(資源) >「Metrics Explorer」。Metrics Explorer 會為您呼叫 API 方法。

    前往 Metrics Explorer 頁面

如需指標與時間序列的介紹,請參閱指標、時間序列和資源一文。

總覽

每一次呼叫 timeSeries.list 方法,都可以從單一指標類型傳回任何數量的時間序列。例如,如果您正在使用 Google Compute Engine,則 compute.googleapis.com/instance/cpu/usage_time 指標類型會針對您的每個 VM 執行個體具有單獨的時間序列。

您可以提供以下資訊來指定您需要哪些時間序列資料:

  • 指定指標類型的篩選器運算式。或者,篩選器會指定產生時間序列的資源,或為時間序列中的某些標籤指定值,以選取指標時間序列的子集。
  • 限制傳回多少資料的時間間隔。
  • 或者,指定如何結合多個時間序列,以產生資料的匯總摘要。詳情請參閱匯總資料一節中的範例。

時間序列篩選器

您可將時間序列篩選器傳送至 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")
    

    請注意,label 是正確的,但實際指標物件會將 labels 做為其金鑰使用。

  • 篩選器可將時間序列限制為包含特定受控資源類型:

    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,則其會測量累計結果或隨時間變化。如果是「期間」指標,則必須同時提供間隔的開始和結束時間,而且開始時間不得晚於結束時間。

詳情請參閱指標種類

基本 list 作業

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

動手操作

按一下 [Execute] (執行) 按鈕之前,請先將 [PROJECT_ID] 變更為您的專案 ID。

範例輸出顯示了兩個不同 VM 執行個體的時間序列:

{
  "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 呼叫疑難排解一文。

範例:取得時間序列資料

此範例會從 Compute Engine 執行個體傳回過去 20 分鐘內 timeSeries.list 要求可用的所有資訊,其中包括指標資料。

通訊協定

通訊協定範例會進一步限制輸出,以便更能在回應方塊中管理傳回的資料。此範例會使用不同的欄位值:

  • filter 值現在將時間序列限制於單一 VM 執行個體。
  • 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

動手操作

按一下 [Execute] (執行) 按鈕之前,請先將 [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 分鐘期間的值計算平均。

此範例將每個時間序列二十個測量值轉換為每個時間序列兩個測量值。這項操作有兩個優點:精簡資料,並以 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

先前的範例中顯示的單一執行個體篩選器已遭刪除:這項查詢傳回的資料少很多,因此不需要將其限制為一個 VM 執行個體。

動手操作

按一下 [Execute] (執行) 按鈕之前,請先將 [PROJECT_ID] 變更為您的專案 ID,並將結束時間調整為最近的值,而將開始時間設為 20 分鐘之前。

在以下範例結果中,三個 VM 執行個體都各有一個時間序列。每個時間序列都有兩個資料點,即 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 呼叫疑難排解一文。

範例:跨時間序列化約

此範例延伸了上一個範例,將三個 VM 執行個體中完成校正的時間序列結合成單一時間序列,呈現所有執行個體的平均使用率。

通訊協定

以下是 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

動手操作

按一下 [Execute] (執行) 按鈕之前,請先將 [PROJECT_ID] 變更為您的專案 ID,並將結束時間調整為最近的值,而將開始時間設為 20 分鐘之前。

以下範例結果只有一個時間序列及兩個資料點。每個資料點都是這段期間三個 VM 執行個體之間的平均使用率:

{
 "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
需要協助嗎?請前往我們的支援網頁