指標データを読み取る

時系列データを読み取る方法について説明します。

もっと見る

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

C#

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


// readTimeSeriesValue reads the TimeSeries for the value specified by metric type in a time window from the last 20 minutes.
func readTimeSeriesValue(projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	startTime := time.Now().UTC().Add(time.Minute * -20).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, %w ", err)
		}
		log.Printf("%+v\n", resp)
	}

	return nil
}

Java

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);

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

Node.js

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

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

async function readTimeSeriesData() {
  /**
   * 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));
    });
  });
}
readTimeSeriesData();

PHP

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest\TimeSeriesView;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Protobuf\Timestamp;

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

    $projectName = 'projects/' . $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 = TimeSeriesView::FULL;
    $listTimeSeriesRequest = (new ListTimeSeriesRequest())
        ->setName($projectName)
        ->setFilter($filter)
        ->setInterval($interval)
        ->setView($view);

    $result = $metrics->listTimeSeries($listTimeSeriesRequest);

    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

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"

now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {
        "end_time": {"seconds": seconds, "nanos": nanos},
        "start_time": {"seconds": (seconds - 1200), "nanos": nanos},
    }
)

results = client.list_time_series(
    request={
        "name": project_name,
        "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        "interval": interval,
        "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
    }
)
for result in results:
    print(result)

Ruby

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

interval = Google::Cloud::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i,
                                                    nanos:   now.nsec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 1200,
                                                      nanos:   now.nsec
filter = 'metric.type = "compute.googleapis.com/instance/cpu/utilization"'
view = Google::Cloud::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL

results = client.list_time_series name:     project_name,
                                  filter:   filter,
                                  interval: interval,
                                  view:     view
results.each do |result|
  p result
end

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。