使用 API 建立使用者定義的指標

本文說明如何使用 Cloud Monitoring API 建立使用者定義指標,以及如何寫入這類指標資料。使用者定義的指標與內建 Cloud Monitoring 指標使用相同的元素:

  • 一組資料點。
  • 指標類型資訊,可說明資料點代表的內容。
  • 受監控資源資訊,可瞭解資料點的來源。

使用者定義指標 (有時稱為自訂指標) 的使用方式與內建指標相同。也就是說,您可以為這項指標資料建立圖表和快訊。

記錄指標是使用者定義指標的一種,但您無法使用 Cloud Monitoring API 建立這類指標。記錄指標會從記錄項目取得指標資料,但 Monitoring API 無法指定從記錄項目擷取指標資料的方式。請改用 Cloud Logging 建立記錄指標。建立記錄指標時,Logging 會建立本文件所述的結構,並將指標資料傳送至 Cloud Monitoring。如要瞭解如何建立記錄指標,請參閱下列文件:

如要檢測應用程式,建議您使用開放原始碼、與供應商無關的檢測架構 (例如 OpenTelemetry),而非供應商和產品專屬的 API 或用戶端程式庫。如要瞭解這些架構,請參閱「 檢測和觀測能力」和「選擇檢測方法」。

事前準備

如要瞭解所有指標的基礎結構,請參閱「指標、時間序列和資源」。

如要使用 Cloud Monitoring,您必須具有啟用計費功能的 Google Cloud 專案,如有需要,請按照下列步驟操作:

  1. 在 Google Cloud 控制台的專案選擇器頁面中,選取或建立 Google Cloud 專案。

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您在專案中獲派角色,即可選取該專案。
    • 建立專案:如要建立專案,您需要專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色。

    前往專案選取器

  2. 確認專案已啟用計費功能 Google Cloud 。

  3. 確認已啟用 Monitoring API。詳情請參閱「啟用 Monitoring API」。
  4. 如果應用程式在 Google Cloud以外的環境執行, Google Cloud 專案必須使用本機應用程式預設憑證 (ADC) 驗證應用程式。詳情請參閱「為地端部署或其他雲端服務供應商設定 ADC」。

建立使用者定義的指標類型

如要建立使用者定義的指標,您可以定義 MetricDescriptor 物件,指定指標的各種資訊,也可以寫入指標資料。寫入指標資料時,Monitoring 會根據您提供的資料結構建立指標描述元。如要瞭解如何設計指標描述元,請參閱使用者定義指標的指標描述元。

自動建立指標描述元

如果您在使用者定義指標的指標描述元尚不存在時寫入指標資料,系統會自動建立指標描述元。不過,這個新的指標描述元可能與您想要的不完全相同;自動建立指標描述元的時候,會需要使用一些假設和預設值。

當呼叫 timeSeries.create 時,如果 TimeSeries 物件參照的 Metric 物件指定了不存在的指標類型名稱,Cloud Monitoring 就會建立新的 MetricDescriptor。Cloud Monitoring 會根據下列規則填入 MetricDescriptor:

  • type:系統會從 Metric 物件的 type 欄位複製類型。
  • name:系統會從方法呼叫中的專案 ID 與 Metric 物件中的 type 值來建立名稱。
  • labels:顯示在 Metric 物件中的標籤。新指標描述元中的每個標籤描述元都有下列欄位:
    • key:Metric 物件中的標籤鍵。
    • valueType:STRING
    • description:未設定
  • metricKind:除非您指定 TimeSeries 物件的 metricKind 參數,否則指標種類會設為 GAUGE。指定 metricKind 時,新指標會含有這個種類。您只能指定 GAUGE 和 CUMULATIVE 種類。
  • valueType:值類型會從要寫入Point的輸入值取得。值類型必須為 BOOL、INT64、DOUBLE 或 DISTRIBUTION。在 TimeSeries 的 valueType 欄位中指定值類型時,該類型必須與 Point 的類型相符。
  • unit:未設定
  • description: "Auto created custom metric.".
  • displayName:未設定

在單一 timeSeries.create 呼叫中,您可以納入多個參照同一種不存在的指標類型的 TimeSeries 物件。在這種情況下,新指標描述元中的標籤會由 create 呼叫的所有時間序列中 Metric 物件內的所有標籤聯集所組成。

後續步驟:請參閱「寫入使用者定義指標」。

手動建立指標描述元

如要建立指標描述元,請按照下列步驟操作:

  1. 決定指標描述元的結構。如要進一步瞭解如何選擇,請瀏覽內建指標,並查看指標時間序列資料:

    1. 為使用者定義指標選擇指標名稱。

    2. 選擇指標的顯示名稱與說明。顯示名稱會用於 Google Cloud 控制台。

    3. 選擇用來定義使用者定義指標並寫入指標時間序列資料的專案。如果您在多個專案中需要相同的指標,請在每個專案中對指標進行相同的定義。

    4. 判斷指標的種類、值類型和 (選擇性) 單位。 使用者定義指標並不支援所有的值類型與指標種類。如要進一步瞭解這些欄位,請參閱「值類型和指標種類」。

    5. 選擇指標的標籤,也就是名稱、值類型與說明。

  2. 決定要寫入指標資料的受監控資源。請從下列清單中選擇:

  3. 建立 MetricDescriptor 物件,然後將其做為引數傳遞至 metricDescriptors.create 方法的呼叫。

一般而言,使用與現有指標描述元相同的類型名稱來呼叫 metricDescriptors.create 是錯誤的做法。但是,如果新 MetricDescriptor 物件的所有欄位都與現有描述元的欄位完全相符,則這類呼叫並非錯誤,但卻會無效。

在下列範例中,您會建立一個取樣指標。

通訊協定

如要建立指標描述元,請使用 metricDescriptors.create 方法。您可以使用方法參考資料頁面上的 APIs Explorer 小工具來執行這個方法。詳情請參閱 APIs Explorer。

以下是 metricDescriptors.create 的範例參數:

  • 名稱 (網址):projects/[PROJECT_ID]
  • 要求主體:提供如下所示的 MetricDescriptor 物件:

    {
      "name": "",
      "description": "Daily sales records from all branch stores.",
      "displayName": "Sales",
      "type": "custom.googleapis.com/stores/sales",
      "metricKind": "GAUGE",
      "valueType": "DOUBLE",
      "unit": "{USD}",
      "labels": [
        {
          "key": "store_id",
          "valueType": "STRING",
          "description": "The ID of the store."
        },
      ],
    }
    

使用您的專案 ID 取代 [PROJECT_ID,將這些值提供給小工具中的欄位:

「Try this API」(試用這個 API) 對話方塊會填入要求主體,用於建立指標描述元。

按一下 [Execute] (執行) 按鈕來執行這個方法。

試試看!

建立新指標時,MetricDescriptor 中的 name 欄位會遭到忽略,且可以省略。create 方法會傳回已填入 name 欄位的新指標描述元,在這個範例中為:

"name": "projects/[PROJECT_ID]/metricDescriptors/custom.googleapis.com/stores/daily_sales"

舉例來說,如果您想要取得指標的描述元,可以使用這個名稱。

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

public static object CreateMetric(string projectId,
    string metricType = "custom.googleapis.com/stores/daily_sales")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();

    // Prepare custom metric descriptor.      
    MetricDescriptor metricDescriptor = new MetricDescriptor();
    metricDescriptor.DisplayName = "Daily Sales";
    metricDescriptor.Description = "Daily sales records from all branch stores.";
    metricDescriptor.MetricKind = MetricKind.Gauge;
    metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
    metricDescriptor.Type = metricType;
    metricDescriptor.Unit = "{USD}";
    LabelDescriptor labels = new LabelDescriptor();
    labels.Key = "store_id";
    labels.ValueType = LabelDescriptor.Types.ValueType.String;
    labels.Description = "The ID of the store.";
    metricDescriptor.Labels.Add(labels);
    CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
    {
        ProjectName = new ProjectName(projectId),
    };
    request.MetricDescriptor = metricDescriptor;
    // Make the request.
    MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
    Console.WriteLine("Done creating metric descriptor:");
    Console.WriteLine(JObject.Parse($"{response}").ToString());
    return 0;
}

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"google.golang.org/genproto/googleapis/api/label"
	"google.golang.org/genproto/googleapis/api/metric"
	metricpb "google.golang.org/genproto/googleapis/api/metric"
)

// createCustomMetric creates a custom metric specified by the metric type.
func createCustomMetric(w io.Writer, projectID, metricType string) (*metricpb.MetricDescriptor, error) {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return nil, err
	}
	defer c.Close()
	md := &metric.MetricDescriptor{
		Name: "Custom Metric",
		Type: metricType,
		Labels: []*label.LabelDescriptor{{
			Key:         "environment",
			ValueType:   label.LabelDescriptor_STRING,
			Description: "An arbitrary measurement",
		}},
		MetricKind:  metric.MetricDescriptor_GAUGE,
		ValueType:   metric.MetricDescriptor_INT64,
		Unit:        "s",
		Description: "An arbitrary measurement",
		DisplayName: "Custom Metric",
	}
	req := &monitoringpb.CreateMetricDescriptorRequest{
		Name:             "projects/" + projectID,
		MetricDescriptor: md,
	}
	m, err := c.CreateMetricDescriptor(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("could not create custom metric: %w", err)
	}

	fmt.Fprintf(w, "Created %s\n", m.GetName())
	return m, nil
}

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Your Google Cloud Platform project ID
final String projectId = System.getProperty("projectId");

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ProjectName projectName = ProjectName.of(projectId);

  MetricDescriptor descriptor =
      MetricDescriptor.newBuilder()
          .setType(type)
          .addLabels(
              LabelDescriptor.newBuilder()
                  .setKey("store_id")
                  .setValueType(LabelDescriptor.ValueType.STRING))
          .setDescription("This is a simple example of a custom metric.")
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .build();

  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(projectName.toString())
          .setMetricDescriptor(descriptor)
          .build();

  descriptor = client.createMetricDescriptor(request);
  System.out.println("Created descriptor " + descriptor.getName());
}

Node.js

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// 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';
async function createMetricDescriptor() {
  const request = {
    name: client.projectPath(projectId),
    metricDescriptor: {
      description: 'Daily sales records from all branch stores.',
      displayName: 'Daily Sales',
      type: 'custom.googleapis.com/stores/daily_sales',
      metricKind: 'GAUGE',
      valueType: 'DOUBLE',
      unit: '{USD}',
      labels: [
        {
          key: 'store_id',
          valueType: 'STRING',
          description: 'The ID of the store.',
        },
      ],
    },
  };

  // Creates a custom metric descriptor
  const [descriptor] = await client.createMetricDescriptor(request);
  console.log('Created custom Metric:\n');
  console.log(`Name: ${descriptor.displayName}`);
  console.log(`Description: ${descriptor.description}`);
  console.log(`Type: ${descriptor.type}`);
  console.log(`Kind: ${descriptor.metricKind}`);
  console.log(`Value Type: ${descriptor.valueType}`);
  console.log(`Unit: ${descriptor.unit}`);
  console.log('Labels:');
  descriptor.labels.forEach(label => {
    console.log(`  ${label.key} (${label.valueType}) - ${label.description}`);
  });
}
createMetricDescriptor();

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Api\LabelDescriptor;
use Google\Api\MetricDescriptor;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\CreateMetricDescriptorRequest;

/**
 * Create a new metric in Stackdriver Monitoring.
 * Example:
 * ```
 * create_metric($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function create_metric($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;

    $descriptor = new MetricDescriptor();
    $descriptor->setDescription('Daily sales records from all branch stores.');
    $descriptor->setDisplayName('Daily Sales');
    $descriptor->setType('custom.googleapis.com/stores/daily_sales');
    $descriptor->setMetricKind(MetricDescriptor\MetricKind::GAUGE);
    $descriptor->setValueType(MetricDescriptor\ValueType::DOUBLE);
    $descriptor->setUnit('{USD}');
    $label = new LabelDescriptor();
    $label->setKey('store_id');
    $label->setValueType(LabelDescriptor\ValueType::STRING);
    $label->setDescription('The ID of the store.');
    $labels = [$label];
    $descriptor->setLabels($labels);
    $createMetricDescriptorRequest = (new CreateMetricDescriptorRequest())
        ->setName($projectName)
        ->setMetricDescriptor($descriptor);

    $descriptor = $metrics->createMetricDescriptor($createMetricDescriptorRequest);
    printf('Created a metric: ' . $descriptor->getName() . PHP_EOL);
}

Python

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.api import label_pb2 as ga_label
from google.api import metric_pb2 as ga_metric
from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
descriptor = ga_metric.MetricDescriptor()
descriptor.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
descriptor.description = "This is a simple example of a custom metric."

labels = ga_label.LabelDescriptor()
labels.key = "TestLabel"
labels.value_type = ga_label.LabelDescriptor.ValueType.STRING
labels.description = "This is a test label"
descriptor.labels.append(labels)

descriptor = client.create_metric_descriptor(
    name=project_name, metric_descriptor=descriptor
)
print("Created {}.".format(descriptor.name))

Ruby

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

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

# Example metric type
# metric_type = "custom.googleapis.com/my_metric"

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

descriptor = Google::Api::MetricDescriptor.new(
  type:        metric_type,
  metric_kind: Google::Api::MetricDescriptor::MetricKind::GAUGE,
  value_type:  Google::Api::MetricDescriptor::ValueType::DOUBLE,
  description: "This is a simple example of a custom metric."
)

result = client.create_metric_descriptor name:              project_name,
                                         metric_descriptor: descriptor
p "Created #{result.name}"
p result

如果遇到問題,請參閱「排解 API 呼叫問題」。

後續步驟:請參閱「寫入使用者定義指標」。

撰寫使用者定義的指標

您只能將資料寫入使用者定義指標的指標類型。如要寫入資料,請使用 timeSeries.create 方法。如果時間序列存在,這個方法會將新的資料點附加至現有時間序列。如果時間序列不存在,這個方法會建立時間序列並附加資料。

您可以將 TimeSeries 物件的清單傳送到 timeSeries.create,藉以寫入資料點。清單大小最多 200 筆,且清單中每個物件都必須指定不同的時間序列。

  • metric 和 resource 欄位的值會識別特定 TimeSeries 物件。這些欄位代表資料的指標類型,以及收集資料的受監控資源。
  • 省略 metricKind 和 valueType 欄位;寫入資料點時,會忽略這兩個欄位。
  • 每個 TimeSeries 物件都只能包含單一 Point 物件:

    • 資料點的值與時間間隔必須與指標類型的定義保持一致。如要瞭解不同指標種類的時間間隔,請參閱TimeInterval。
    • 資料點的時間間隔必須晚於已在時間序列中的任何資料點。
    • 間隔的結束時間在過去不得超過 25 小時,在未來不得超過五分鐘。
  • 如要將多個資料點寫入相同的時間序列,請針對每個資料點單獨呼叫 timeSeries.create 方法。請勿以高於每 5 秒一個資料點的速度,將資料寫入單一時間序列。如果您要將資料點新增至不同的時間序列,則沒有頻率限制。

通訊協定

如要寫入指標資料,請使用 timeSeries.create 方法。您可以使用方法參考資料頁面上的 APIs Explorer 小工具來執行這個方法。詳情請參閱 API Explorer。

如要將資料點寫入在手動建立指標描述元一節中建立的 stores/daily_sales 指標,請按照下列步驟操作:

  1. 前往 timeSeries.create 的參考資料頁面。
  2. 將下列參數提供給 APIs Explorer 小工具。
  3. 按一下 [Execute] (執行) 按鈕。

使用下列範例參數:

  • name:projects/[PROJECT_ID]
  • 要求主體:包含 TimeSeries 物件的清單。下列範例清單中只包含一個時間序列。

    {
     "timeSeries": [
      {
       "metric": {
        "type": "custom.googleapis.com/my_metric",
        "labels": {
         "my_label": "my_value"
        }
       },
       "resource": {
        "type": "gce_instance",
        "labels": {
         "project_id": "[PROJECT_ID]",
         "instance_id": "1234567890123456789",
         "zone": "us-central1-f"
        }
       },
       "points": [
        {
         "interval": {
          "endTime": "2018-06-01T10:00:00-04:00"
         },
         "value": {
          "doubleValue": 123.45
         }
        }
       ]
      }
     ]
    }
    

試試看!

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

public static object WriteTimeSeriesData(string projectId)
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    ProjectName name = new ProjectName(projectId);
    // Prepare a data point. 
    Point dataPoint = new Point();
    TypedValue salesTotal = new TypedValue();
    salesTotal.DoubleValue = 123.45;
    dataPoint.Value = salesTotal;
    Timestamp timeStamp = new Timestamp();
    timeStamp.Seconds = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    TimeInterval interval = new TimeInterval();
    interval.EndTime = timeStamp;
    dataPoint.Interval = interval;

    // Prepare custom metric.
    Metric metric = new Metric();
    metric.Type = "custom.googleapis.com/stores/daily_sales";
    metric.Labels.Add("store_id", "Pittsburgh");

    // Prepare monitored resource.
    MonitoredResource resource = new MonitoredResource();
    resource.Type = "global";
    resource.Labels.Add("project_id", projectId);

    // Create a new time series using inputs.
    TimeSeries timeSeriesData = new TimeSeries();
    timeSeriesData.Metric = metric;
    timeSeriesData.Resource = resource;
    timeSeriesData.Points.Add(dataPoint);

    // Add newly created time series to list of time series to be written.
    IEnumerable timeSeries = new List { timeSeriesData };
    // Write time series data.
    metricServiceClient.CreateTimeSeries(name, timeSeries);
    Console.WriteLine("Done writing time series data:");
    Console.WriteLine(JObject.Parse($"{timeSeriesData}").ToString());
    return 0;
}

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


// writeTimeSeriesValue writes a value for the custom metric created
func writeTimeSeriesValue(projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	now := &timestamp.Timestamp{
		Seconds: time.Now().Unix(),
	}
	req := &monitoringpb.CreateTimeSeriesRequest{
		Name: "projects/" + projectID,
		TimeSeries: []*monitoringpb.TimeSeries{{
			Metric: &metricpb.Metric{
				Type: metricType,
				Labels: map[string]string{
					"environment": "STAGING",
				},
			},
			Resource: &monitoredres.MonitoredResource{
				Type: "gce_instance",
				Labels: map[string]string{
					"instance_id": "test-instance",
					"zone":        "us-central1-f",
				},
			},
			Points: []*monitoringpb.Point{{
				Interval: &monitoringpb.TimeInterval{
					StartTime: now,
					EndTime:   now,
				},
				Value: &monitoringpb.TypedValue{
					Value: &monitoringpb.TypedValue_Int64Value{
						Int64Value: rand.Int63n(10),
					},
				},
			}},
		}},
	}
	log.Printf("writeTimeseriesRequest: %+v\n", req)

	err = c.CreateTimeSeries(ctx, req)
	if err != nil {
		return fmt.Errorf("could not write time series value, %w ", err)
	}
	return nil
}

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

String projectId = System.getProperty("projectId");

// Prepares an individual data point
TimeInterval interval =
    TimeInterval.newBuilder()
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();
TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

List pointList = new ArrayList<>();
pointList.add(point);

ProjectName name = ProjectName.of(projectId);

// Prepares the metric descriptor
Map, String> metricLabels = new HashMap<>();
Metric metric =
    Metric.newBuilder()
        .setType("custom.googleapis.com/my_metric")
        .putAllLabels(metricLabels)
        .build();

// Prepares the monitored resource descriptor
Map, String> resourceLabels = new HashMap<>();
resourceLabels.put("instance_id", "1234567890123456789");
resourceLabels.put("zone", "us-central1-f");

MonitoredResource resource =
    MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

// Prepares the time series request
TimeSeries timeSeries =
    TimeSeries.newBuilder()
        .setMetric(metric)
        .setResource(resource)
        .addAllPoints(pointList)
        .build();

List timeSeriesList = new ArrayList<>();
timeSeriesList.add(timeSeries);

CreateTimeSeriesRequest request =
    CreateTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .addAllTimeSeries(timeSeriesList)
        .build();

// Writes time series data
try (final MetricServiceClient client = MetricServiceClient.create();) {
  client.createTimeSeries(request);
}
System.out.println("Done writing time series value.");

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 writeTimeSeriesData() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const dataPoint = {
    interval: {
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    value: {
      doubleValue: 123.45,
    },
  };

  const timeSeriesData = {
    metric: {
      type: 'custom.googleapis.com/stores/daily_sales',
      labels: {
        store_id: 'Pittsburgh',
      },
    },
    resource: {
      type: 'global',
      labels: {
        project_id: projectId,
      },
    },
    points: [dataPoint],
  };

  const request = {
    name: client.projectPath(projectId),
    timeSeries: [timeSeriesData],
  };

  // Writes time series data
  const result = await client.createTimeSeries(request);
  console.log('Done writing time series data.', result);
}
writeTimeSeriesData();

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Api\Metric;
use Google\Api\MonitoredResource;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\CreateTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\Point;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\TimeSeries;
use Google\Cloud\Monitoring\V3\TypedValue;
use Google\Protobuf\Timestamp;

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

    $projectName = 'projects/' . $projectId;

    $endTime = new Timestamp();
    $endTime->setSeconds(time());
    $interval = new TimeInterval();
    $interval->setEndTime($endTime);

    $value = new TypedValue();
    $value->setDoubleValue(123.45);

    $point = new Point();
    $point->setValue($value);
    $point->setInterval($interval);
    $points = [$point];

    $metric = new Metric();
    $metric->setType('custom.googleapis.com/stores/daily_sales');
    $labels = ['store_id' => 'Pittsburg'];
    $metric->setLabels($labels);

    $resource = new MonitoredResource();
    $resource->setType('global');
    $labels = ['project_id' => $projectId];
    $resource->setLabels($labels);

    $timeSeries = new TimeSeries();
    $timeSeries->setMetric($metric);
    $timeSeries->setResource($resource);
    $timeSeries->setPoints($points);
    $createTimeSeriesRequest = (new CreateTimeSeriesRequest())
        ->setName($projectName)
        ->setTimeSeries([$timeSeries]);

    $metrics->createTimeSeries($createTimeSeriesRequest);

    printf('Done writing time series data.' . PHP_EOL);
}

Python

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.cloud import monitoring_v3

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

series = monitoring_v3.TimeSeries()
series.metric.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
series.resource.type = "gce_instance"
series.resource.labels["instance_id"] = "1234567890123456789"
series.resource.labels["zone"] = "us-central1-c"
series.metric.labels["TestLabel"] = "My Label Data"
now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {"end_time": {"seconds": seconds, "nanos": nanos}}
)
point = monitoring_v3.Point({"interval": interval, "value": {"double_value": 3.14}})
series.points = [point]
client.create_time_series(name=project_name, time_series=[series])

Ruby

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

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

# Example metric type
# metric_type = "custom.googleapis.com/my_metric"

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

series = Google::Cloud::Monitoring::V3::TimeSeries.new
series.metric = Google::Api::Metric.new type: metric_type

resource = Google::Api::MonitoredResource.new type: "global"
resource.labels["project_id"] = project_id
series.resource = resource

point = Google::Cloud::Monitoring::V3::Point.new
point.value = Google::Cloud::Monitoring::V3::TypedValue.new double_value: 3.14
now = Time.now
end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.nsec
point.interval = Google::Cloud::Monitoring::V3::TimeInterval.new end_time: end_time
series.points << point

client.create_time_series name: project_name, time_series: [series]
p "Time series created."

如果遇到問題,請參閱「排解 API 呼叫問題」。

刪除使用者定義指標

如要刪除使用者定義指標,請刪除指標描述元。 您無法刪除儲存在 Google Cloud 專案中的時間序列資料,但刪除指標描述元會導致無法存取資料。資料會根據資料保留政策過期並刪除。

您無法刪除內建指標的指標描述元。

如要刪除指標描述元,請呼叫 metricDescriptors.delete 方法。

通訊協定

如要刪除指標描述元,請使用 metricDescriptors.delete 方法。您可以使用方法參考資料頁面上的 APIs Explorer 小工具來執行這個方法。詳情請參閱 API Explorer。

如要刪除在手動建立指標描述元一節中建立的 stores/daily_sales 指標,請按照以下步驟操作:

  1. 前往 metricDescriptors.delete 的參考資料頁面:
  2. 將指標描述元的名稱提供給 API Explorer 小工具:

    name:projects/[PROJECT_ID]/metricDescriptors/custom.googleapis.com/stores/daily_sales

  3. 按一下 [Execute] (執行) 按鈕。

試試看!

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

public static object DeleteMetric(string projectId, string metricType)
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
    // Make the request.
    metricServiceClient.DeleteMetricDescriptor(name);
    Console.WriteLine($"Done deleting metric descriptor: {name}");
    return 0;
}

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
)

// deleteMetric deletes the given metric. name should be of the form
// "projects/PROJECT_ID/metricDescriptors/METRIC_TYPE".
func deleteMetric(w io.Writer, name string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	req := &monitoringpb.DeleteMetricDescriptorRequest{
		Name: name,
	}

	if err := c.DeleteMetricDescriptor(ctx, req); err != nil {
		return fmt.Errorf("could not delete metric: %w", err)
	}
	fmt.Fprintf(w, "Deleted metric: %q\n", name)
	return nil
}

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

final String projectId = System.getProperty("projectId");
try (final MetricServiceClient client = MetricServiceClient.create();) {
  MetricDescriptorName metricName = MetricDescriptorName.of(projectId, type);
  client.deleteMetricDescriptor(metricName);
  System.out.println("Deleted descriptor " + type);
}

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 deleteMetricDescriptor() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const metricId = 'custom.googleapis.com/stores/daily_sales';

  const request = {
    name: client.projectMetricDescriptorPath(projectId, metricId),
  };

  // Deletes a metric descriptor
  const [result] = await client.deleteMetricDescriptor(request);
  console.log(`Deleted ${metricId}`, result);
}
deleteMetricDescriptor();

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\DeleteMetricDescriptorRequest;

/**
 * Example:
 * ```
 * delete_metric($projectId, $databaseId);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $metricId  The ID of the Metric Descriptor to delete
 */
function delete_metric($projectId, $metricId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $metricPath = $metrics->metricDescriptorName($projectId, $metricId);
    $deleteMetricDescriptorRequest = (new DeleteMetricDescriptorRequest())
        ->setName($metricPath);
    $metrics->deleteMetricDescriptor($deleteMetricDescriptorRequest);

    printf('Deleted a metric: ' . $metricPath . PHP_EOL);
}

Python

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
client.delete_metric_descriptor(name=descriptor_name)
print("Deleted metric descriptor {}.".format(descriptor_name))

Ruby

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

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

# Example metric type
# metric_type = "custom.googleapis.com/my_metric"

client = Google::Cloud::Monitoring.metric_service
metric_name = client.metric_descriptor_path project:           project_id,
                                            metric_descriptor: metric_type

client.delete_metric_descriptor name: metric_name
p "Deleted metric descriptor #{metric_name}."

如果遇到問題,請參閱「排解 API 呼叫問題」。

修改使用者定義指標

如要修改使用者定義指標,請更新定義指標的 MetricDescriptor 物件。目前僅支援新增標籤。

如要為現有使用者定義指標新增標籤,請使用 timeSeries.create 方法,並在時間序列資料中加入新標籤。如果您嘗試寫入的標籤有效,且標籤總數少於 30 個,系統就會將標籤新增至指標描述元。

接著,就像一開始就有標籤一樣,系統會寫入時間序列資料。

如要執行新增標籤之外的其他操作,則必須刪除並重新建立指標描述元。在這種情況下,您會遺失之前針對舊指標描述元收集的所有時間序列資料。詳情請參閱「刪除使用者定義的指標」。

您無法重新命名指標。

後續步驟