측정항목 데이터를 생성하는 VM 인스턴스 나열

지정된 필터와 일치하는 시계열 데이터가 있는 VM을 나열하는 방법을 설명합니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

C#

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

// 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: %w", err)
	}
	defer client.Close()
	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: %w", err)
		}
		fmt.Fprintf(w, "\t%v\n", resp.GetMetric().GetLabels()["instance_name"])
	}
	fmt.Fprintln(w, "Done")
	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("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
        .setInterval(interval)
        .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

ListTimeSeriesRequest request = requestBuilder.build();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);
  System.out.println("Got timeseries headers: ");
  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 readTimeSeriesFields() {
  /**
   * 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);
  });
}
readTimeSeriesFields();

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_fields($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_fields(string $projectId, int $minutesAgo = 20): void
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

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

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

    printf('Found data points for the following instances:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        printf($timeSeries->getMetric()->getLabels()['instance_name'] . 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.HEADERS,
    }
)
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::HEADERS

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 샘플 브라우저를 참조하세요.