Como ler dados de métricas

Nesta página, explicamos como ler dados de métrica, também chamados de dados de série temporal, usando o método timeSeries.list na API Monitoring. Há várias maneiras de usá-lo:

  • Para executar o método list sem gravar códigos, os exemplos nas guias PROTOCOLO nesta página usam o API Explorer com base em formulários. Consulte API Explorer para ver mais informações sobre essa ferramenta.

  • Para saber como usar o método list nas linguagens de programação selecionadas, consulte as amostras de códigos executáveis nesta página.

  • Para navegar pelos dados de série temporal e ver um gráfico deles, acesse Resources > Metrics Explorer na seção "Stackdriver Monitoring" do Console do Google Cloud Platform. O Metrics Explorer chama os métodos de API para você.

    Acessar a página "Metrics Explorer"

Para ver uma introdução a métricas e séries temporais, consulte Métricas, séries temporais e recursos.

Visão geral

Cada chamada para o método timeSeries.list retorna qualquer número de séries temporais de um único tipo de métrica. Por exemplo, se você estiver usando o Google Compute Engine, o tipo de métrica compute.googleapis.com/instance/cpu/usage_time terá uma série temporal separada para cada uma das instâncias de VM.

Forneça o seguinte para especificar quais dados de série temporal você quer:

  • Uma expressão de filtro que especifica o tipo de métrica. Como opção, o filtro seleciona um subconjunto da série temporal da métrica, especificando os recursos que produzem a série temporal ou os valores para determinados rótulos na série temporal.
  • Um intervalo de tempo que limita a quantidade de dados retornados.
  • Como opção, uma especificação de como combinar várias séries temporais para produzir um resumo agregado dos dados. Para mais informações, consulte Como agregar dados para alguns exemplos.

Filtros da série temporal

Para especificar quais séries temporais você quer recuperar, passe um filtro da série temporal para o método list. Veja a seguir os componentes de filtro comumente fornecidos:

  • O filtro precisa especificar um único tipo de métrica. Por exemplo:

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

    Para recuperar métricas personalizadas, altere "metric.type" no filtro para custom.googleapis.com ou outro prefixo, se usado. external.googleapis.com é utilizado com frequência.

  • Com o filtro, é possível especificar valores para os rótulos de dimensão da métrica. O tipo de métrica determina quais rótulos estão presentes. Por exemplo:

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

    Observe que label está correto, mas o objeto da métrica real usa labels como chave.

  • O filtro pode limitar as séries temporais às que contêm um tipo de recurso monitorado específico:

    resource.type = "gae_app"
    

Os componentes do filtro podem ser combinados em um único filtro de série temporal, como a seguir:

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")

Se você não especificar valores para todos os rótulos de métricas, o método list retornará uma série temporal para cada combinação de valores nos rótulos não especificados. O método retornará somente séries temporais que tenham dados.

Intervalos de tempo

É necessário especificar interval.startTime e interval.endTime ao chamar o método timeSeries.list. O período resultante inclui o horário de término, mas não o horário de início, a menos que ambos sejam iguais. Isso pode ser confuso. Por exemplo, considere estes exemplos de intervalos (start, end]:

(T, T+1]
Esse intervalo não contém T.
(T-1, T]
Esse intervalo contém T.
(T, T]
Sendo um caso especial e incomum, esse intervalo inclui apenas o tempo T. Se você omitir o horário de início, esse será o intervalo recebido.

Valores em intervalos de tempo

Os horários de início e de término precisam ser especificados como strings no formato RFC 3339. Por exemplo:

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

O comando date -Iseconds no Linux é usado para gerar carimbos de data e hora.

Extensão dos intervalos de tempo

Um intervalo de tempo é especificado por um horário de início e término. No entanto, o horário de início não é exigido pela API. Se ele não for especificado, seu valor padrão será o horário de término. Isso faz sentido semanticamente apenas para as métricas GAUGE, que avaliam períodos.

Se a métrica for CUMULATIVE ou DELTA, ela avaliará um acúmulo ou alteração ao longo do tempo. Para métricas "ao longo do tempo", é necessário fornecer os horários de início e término do intervalo, e o de início precisa ser anterior ao de término.

Consulte Tipos de métricas para ver mais informações.

Operações básicas de listagem

É possível usar o método timeSeries.list para retornar dados simples, brutos ou altamente processados. Nesta seção, ilustramos alguns usos básicos.

Exemplo: como listar séries temporais disponíveis

Neste exemplo, mostramos como listar apenas os nomes e as descrições da série temporal que correspondem a um filtro, em vez de retornar todos os dados disponíveis:

Protocolo

Estes são os parâmetros de amostra de timeSeries.list:

  • name: projects/[PROJECT_ID]
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric

Faça o teste!

Antes de clicar no botão Executar, altere [PROJECT_ID] para o ID do projeto.

O exemplo de saída mostra séries temporais para duas instâncias de VM diferentes:

{
  "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

Consulte Solução de problemas de chamadas da API se tiver dificuldade.

Exemplo: como receber dados de série temporal

Neste exemplo, retornamos todas as informações disponíveis para a solicitação timeSeries.list das instâncias do Compute Engine nos últimos 20 minutos. Isso inclui os dados de métrica.

Protocolo

O exemplo de protocolo limita ainda mais a saída para que os dados retornados sejam mais gerenciáveis na caixa de resposta. São usados valores de campo diferentes neste exemplo:

  • O valor de filter agora limita a série temporal a uma única instância de VM.
  • O valor de fields agora especifica somente o horário e o valor das medidas.

Isso limita a quantidade de dados de séries temporais retornada no resultado.

Estes são os parâmetros de amostra de timeSeries.list:

  • name: projects/[PROJECT_ID]
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization" AND metric.label.instance_name = "[YOUR_INSTANCE_NAME]"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.points.interval.endTime,timeSeries.points.value

Faça o teste!

Antes de clicar no botão Executar, altere [PROJECT_ID] e [YOUR_INSTANCE_NAME] para os valores no seu projeto. Além disso, defina o horário de término como um momento recente e o de início para 20 minutos antes.

A solicitação retorna um resultado como este:

{
 "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

Os dados retornados incluem 20 pontos de dados em cada série temporal durante o período de 20 minutos. Isso porque as métricas do Compute Engine são coletadas a cada minuto. Para saber mais, consulte Latência dos dados de métrica. A API retorna os pontos de dados em cada série temporal em ordem de tempo inversa. Essa ordem de pontos não causa modificações.

Consulte Solução de problemas de chamadas da API se tiver dificuldade.

Como agregar dados

O método timeSeries.list pode executar agregações e reduções estatísticas nos dados das séries temporais retornadas. Nas seções a seguir, demonstramos dois exemplos. Consulte a documentação do método para ver mais opções.

Exemplo: como alinhar séries temporais

Neste exemplo, reduzimos as 20 medições de utilização individual em cada série temporal para apenas duas medições: a utilização média dos dois períodos de 10 minutos dentro do intervalo de 20 minutos. Os dados de cada série temporal são alinhados em períodos de 10 minutos (600 segundos). Depois, é feita a média dos valores em cada período de 10 minutos.

Neste exemplo, reduzimos as medições por série temporal de 20 para 2. Essa operação tem duas vantagens: uniformiza os dados e alinha os dados de todas as séries temporais em limites exatos de 10 minutos. Os dados podem então ser processados posteriormente.

Protocolo

Estes são os parâmetros de amostra de timeSeries.list:

  • name: projects/[PROJECT_ID]
  • aggregation.alignmentPeriod: 600s
  • aggregation.perSeriesAligner: ALIGN_MEAN
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric,timeSeries.points

O filtro de uma única instância mostrado no exemplo anterior foi removido: essa consulta retorna muito menos dados. Portanto, há menos necessidade de restringi-la a uma instância de VM.

Faça o teste!

Antes de clicar no botão Executar, altere [PROJECT_ID] para o código do seu projeto. Além disso, ajuste o horário de término como um momento recente e o de início para 20 minutos antes.

O resultado de exemplo a seguir tem uma série temporal para cada uma das três instâncias de VM. Cada série temporal tem dois pontos de dados, que é a utilização média dos períodos de alinhamento de 10 minutos:

{
 "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

Consulte Solução de problemas de chamadas da API se tiver dificuldade.

Exemplo: como fazer a redução em séries temporais

Este exemplo é uma extensão do anterior. Ele combina a série temporal alinhada das três instâncias de VM em uma única série temporal que tem a utilização média de todas as instâncias.

Protocolo

Veja a seguir os parâmetros de amostra de timeSeries.list, que diferem do exemplo anterior apenas por incluir aggregation.crossSeriesReducer:

  • name: projects/[PROJECT_ID]
  • aggregation.alignmentPeriod: 600s
  • aggregation.crossSeriesReducer: REDUCE_MEAN
  • aggregation.perSeriesAligner: ALIGN_MEAN
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric,timeSeries.points

Faça o teste!

Antes de clicar no botão Executar, altere [PROJECT_ID] para o código do seu projeto. Além disso, ajuste o horário de término como um momento recente e o de início para 20 minutos antes.

O resultado da amostra a seguir tem apenas uma série temporal e dois pontos de dados. Cada ponto é a média da utilização entre as três instâncias de VM durante o período:

{
 "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

Consulte Solução de problemas de chamadas da API se tiver dificuldade.

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Stackdriver Monitoring
Precisa de ajuda? Acesse nossa página de suporte.