列出指标和资源类型

本文档介绍了如何使用 Cloud Monitoring API 获取列表或 以下各项的说明:

  • 您的项目中定义的用户定义的指标类型。
  • 包含项目中的时间序列数据的第三方指标类型。由 BindPlane 生成的指标 都是第三方指标的示例BindPlane 指标 前缀为 workload.googleapis.com/3rd-party-app-name/。 有关受支持的第三方应用指标的完整列表,请参阅 BindPlane 来源文档。
  • Google Cloud 提供的内置指标类型。这些指标类型有助于 您可以自行设计用户定义的指标您还可以找到 这些指标;请参阅指标列表
  • 可用于您的项目的受监控的资源类型。您还可以在文档中找到这些资源的相关信息;请参阅受监控的资源列表
有多种方式可以使用本文档介绍的 API 方法:

  • 为了在不编写任何代码的情况下运行这些方法,本页面上的协议标签页中的示例使用基于表单的 API Explorer。(请参阅 APIs Explorer 有关该工具的详细信息。)

  • 如需了解如何使用所选编程语言中的方法, 请参阅本页的可运行代码示例

准备工作

列出指标描述符

指标描述符是定义指标的架构。 要查找您感兴趣的指标的详细信息,请浏览可用的指标描述符:

  • 内置指标:您可以向任何现有项目发出 API 请求,也可以使用指标列表文档。
  • 用户定义的指标和外部指标:您必须发出 API 请求 已定义用户定义的指标或项目的 指标的时间序列数据存在。

如需详细了解指标类型的命名方式,请参阅命名规则

列出指标类型

要获取当前的指标类型列表,请使用 metricDescriptors.list 方法。要减少返回的指标类型数量,请使用过滤条件。如需帮助确定要搜索的指标类型,请参阅值类型和指标种类

协议

  1. 打开 metricDescriptors.list 参考页面。

  2. 在标有尝试此方法的窗格中,输入以下内容:

    • nameprojects/PROJECT_ID。将 PROJECT_ID 替换为 您的 Google Cloud 项目的 ID。
    • 过滤条件metric.type = starts_with("compute.googleapis.com")
  3. 点击执行

以下示例响应显示了检索到的一些指标描述符:

    "metricDescriptors": [
      {
        "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_bytes_count",
        "labels": [{...}],
         ...
         "description": "Count of incoming bytes dropped by the firewall.",
         "displayName": "Dropped bytes",
         "type": "compute.googleapis.com/firewall/dropped_bytes_count",
         ...
      },
      {
         "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count",
         "labels": [{...}],
         ...
         "description": "Count of incoming packets dropped by the firewall.",
         "displayName": "Dropped packets",
         "type": "compute.googleapis.com/firewall/dropped_packets_count",
      },
      ...
    ]

每个描述符中的 type 值用于标识指标描述符, 示例:compute.googleapis.com/firewall/dropped_packets_count。此值有时也称为“指标类型”或“指标类型名称”。

如需以 curl 命令的形式查看请求,请以 HTTP 请求,或在 JavaScript 中,点击 全屏

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object ListMetrics(string projectId)
{
    MetricServiceClient client = MetricServiceClient.Create();
    ProjectName projectName = new ProjectName(projectId);
    PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName);
    foreach (MetricDescriptor metric in metrics)
    {
        Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
    }
    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/api/iterator"
)

// listMetrics lists all the metrics available to be monitored in the API.
func listMetrics(w io.Writer, projectID string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()

	req := &monitoringpb.ListMetricDescriptorsRequest{
		Name: "projects/" + projectID,
	}
	iter := c.ListMetricDescriptors(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Could not list metrics: %w", err)
		}
		fmt.Fprintf(w, "%v\n", resp.GetType())
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

ListMetricDescriptorsRequest request =
    ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();

// Instantiates a client
try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);

  System.out.println("Listing descriptors: ");

  for (MetricDescriptor d : response.iterateAll()) {
    System.out.println(d.getName() + " " + d.getDisplayName());
  }
}

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

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

  // Lists metric descriptors
  const [descriptors] = await client.listMetricDescriptors(request);
  console.log('Metric Descriptors:');
  descriptors.forEach(descriptor => console.log(descriptor.name));
}
listMetricDescriptors();

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

    $projectName = 'projects/' . $projectId;
    $listMetricDescriptorsRequest = (new ListMetricDescriptorsRequest())
        ->setName($projectName);
    $descriptors = $metrics->listMetricDescriptors($listMetricDescriptorsRequest);

    printf('Metric Descriptors:' . PHP_EOL);
    foreach ($descriptors->iterateAllElements() as $descriptor) {
        printf($descriptor->getName() . PHP_EOL);
    }
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
descriptors = client.list_metric_descriptors(name=project_name)
for descriptor in descriptors:
    print(descriptor.type)

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

results = client.list_metric_descriptors name: project_name
results.each do |descriptor|
  p descriptor.type
end

如果遇到困难,请参阅排查 API 调用问题

获取指标描述符

要获取单个指标类型的相关信息,请使用 metricDescriptors.get 方法。 此方法会返回一个指标描述符。

如需检索特定指标描述符,您必须向 API 提供指标的全名。全名由两部分组成:

  • projects/PROJECT_ID/metricDescriptors 组成的前缀。
  • 标识指标描述符的 type 值,例如 compute.googleapis.com/firewall/dropped_packets_count。如需详细了解 type 值,请参阅列出指标类型中的协议标签页。

以下是指标的全名示例:

projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count

协议

获取 Compute Engine /firewall/dropped_packets_count 的描述符 ,请执行以下操作:

  1. 打开 metricDescriptors.list 参考页面。

  2. 在标有尝试此方法的窗格中,输入以下内容:

    • 名称projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count

      PROJECT_ID 替换为您的 Google Cloud 项目的 ID。

  3. 点击执行

以下示例响应显示了该指标的描述符:

    {
        "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count",
        "labels": [
          {
            "key": "instance_name",
            "description": "The name of the VM instance."
          }
        ],
        "metricKind": "DELTA",
        "valueType": "INT64",
        "unit": "1",
        "description": "Count of incoming packets dropped by the firewall.",
        "displayName": "Dropped packets",
        "type": "compute.googleapis.com/firewall/dropped_packets_count",
      }

如需以 curl 命令的形式查看请求,请以 HTTP 请求,或在 JavaScript 中,点击 全屏

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object GetMetricDetails(string projectId, string metricType)
{
    MetricServiceClient client = MetricServiceClient.Create();
    MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
    try
    {
        var response = client.GetMetricDescriptor(name);
        string metric = JObject.Parse($"{response}").ToString();
        Console.WriteLine($"{ metric }");
    }
    catch (Grpc.Core.RpcException ex)
        when (ex.Status.StatusCode == Grpc.Core.StatusCode.NotFound)
    { }
    return 0;
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import (
	"context"
	"fmt"
	"io"

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

// getMetricDescriptor gets the descriptor for the given metricType and prints
// information about it. metricType is the type of the metric, for example
// compute.googleapis.com/firewall/dropped_packets_count.
func getMetricDescriptor(w io.Writer, projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer c.Close()
	req := &monitoringpb.GetMetricDescriptorRequest{
		Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", projectID, metricType),
	}
	resp, err := c.GetMetricDescriptor(ctx, req)
	if err != nil {
		return fmt.Errorf("could not get custom metric: %w", err)
	}

	fmt.Fprintf(w, "Name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
	fmt.Fprintf(w, "Type: %v\n", resp.GetType())
	fmt.Fprintf(w, "Metric Kind: %v\n", resp.GetMetricKind())
	fmt.Fprintf(w, "Value Type: %v\n", resp.GetValueType())
	fmt.Fprintf(w, "Unit: %v\n", resp.GetUnit())
	fmt.Fprintf(w, "Labels:\n")
	for _, l := range resp.GetLabels() {
		fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
	}
	return nil
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

MetricDescriptorName descriptorName = MetricDescriptorName.of(projectId, type);

try (final MetricServiceClient client = MetricServiceClient.create();) {
  MetricDescriptor response = client.getMetricDescriptor(descriptorName);

  System.out.println("Printing metrics descriptor: " + response);
}

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

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

  // Retrieves a metric descriptor
  const [descriptor] = await client.getMetricDescriptor(request);
  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}`);
  });
}
getMetricDescriptor();

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

    $metricName = $metrics->metricDescriptorName($projectId, $metricId);
    $getMetricDescriptorRequest = (new GetMetricDescriptorRequest())
        ->setName($metricName);
    $descriptor = $metrics->getMetricDescriptor($getMetricDescriptorRequest);

    printf('Name: ' . $descriptor->getDisplayName() . PHP_EOL);
    printf('Description: ' . $descriptor->getDescription() . PHP_EOL);
    printf('Type: ' . $descriptor->getType() . PHP_EOL);
    printf('Metric Kind: ' . $descriptor->getMetricKind() . PHP_EOL);
    printf('Value Type: ' . $descriptor->getValueType() . PHP_EOL);
    printf('Unit: ' . $descriptor->getUnit() . PHP_EOL);
    printf('Labels:' . PHP_EOL);
    foreach ($descriptor->getLabels() as $labels) {
        printf('  %s (%s) - %s' . PHP_EOL,
            $labels->getKey(),
            $labels->getValueType(),
            $labels->getDescription());
    }
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
descriptor = client.get_metric_descriptor(name=metric_name)
pprint.pprint(descriptor)

Ruby

如需向 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

descriptor = client.get_metric_descriptor name: metric_name
p descriptor

如果遇到困难,请参阅排查 API 调用问题

列出受监控的资源

受监控的资源是可以受监控的云端实体。要查找具有指标的实体种类,请浏览受监控的资源类型列表。

如需获取受监控的资源的相关信息,您可以向任何现有项目发出 API 请求,也可以使用受监控的资源列表文档。

列出资源类型

要从 Monitoring API 获取受监控的资源类型的当前列表,请使用 monitoredResourceDescriptors.list 方法并提供项目 ID。

协议

  1. 打开monitoredResourceDescriptors.list 参考页面。

  2. 在标记为试用此方法的窗格中,输入以下内容:

    • nameprojects/PROJECT_ID。将“PROJECT_ID”替换为 您的 Google Cloud 项目的 ID。
  3. 点击执行

以下示例响应显示了返回的一些受监控的资源类型:

    {
    "resourceDescriptors": [
    {
      "type": "aiplatform.googleapis.com/Endpoint",
      "displayName": "AI Platform Endpoint",
      "description": "A Cloud AI Platform API Endpoint where Models are deployed into it.",
      "labels": [{...}],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/aiplatform.googleapis.com/Endpoint",
    },
    {
      "type": "aiplatform.googleapis.com/Featurestore",
      "displayName": "AI Platform Feature Store",
      "description": "A Cloud AI Platform Feature Store.",
      "labels": [{...}],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/aiplatform.googleapis.com/Featurestore",
    },

如需采用 curl 命令、HTTP 请求或 JavaScript 格式查看请求,请在 API Explorer 中点击 全屏

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

        public static object ListMonitoredResources(string projectId)
        {
            Console.WriteLine("Starting to List Monitored Resources...");
            MetricServiceClient client = MetricServiceClient.Create();
            ProjectName projectName = new ProjectName(projectId);

            PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor>
                resources = client.ListMonitoredResourceDescriptors(projectName);
            if (resources.Any())
            {
                foreach (MonitoredResourceDescriptor resource in resources.Take(10))
                {
                    Console.WriteLine($"{resource.Name}: {resource.DisplayName}");
                }
            }
            else
            { 
                Console.WriteLine("No resources found.");
            }
            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/api/iterator"
)

// listMonitoredResources lists all the resources available to be monitored.
func listMonitoredResources(w io.Writer, projectID string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()

	req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{
		Name: "projects/" + projectID,
	}
	iter := c.ListMonitoredResourceDescriptors(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Could not list time series: %w", err)
		}
		fmt.Fprintf(w, "%v\n", resp)
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

ListMonitoredResourceDescriptorsRequest request =
    ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build();

System.out.println("Listing monitored resource descriptors: ");

// Instantiates a client
try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListMonitoredResourceDescriptorsPagedResponse response =
      client.listMonitoredResourceDescriptors(request);

  for (MonitoredResourceDescriptor d : response.iterateAll()) {
    System.out.println(d.getType());
  }
}

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

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

  // Lists monitored resource descriptors
  const [descriptors] =
    await client.listMonitoredResourceDescriptors(request);
  console.log('Monitored Resource Descriptors:');
  descriptors.forEach(descriptor => {
    console.log(descriptor.name);
    console.log(`  Type: ${descriptor.type}`);
    if (descriptor.labels) {
      console.log('  Labels:');
      descriptor.labels.forEach(label => {
        console.log(
          `    ${label.key} (${label.valueType}): ${label.description}`
        );
      });
    }
    console.log();
  });
}
listMonitoredResourceDescriptors();

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

/**
 * Example:
 * ```
 * list_resources('your-project-id');
 * ```
 *
 * @param string $projectId Your project ID
 */
function list_resources($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;
    $listMonitoredResourceDescriptorsRequest = (new ListMonitoredResourceDescriptorsRequest())
        ->setName($projectName);
    $descriptors = $metrics->listMonitoredResourceDescriptors($listMonitoredResourceDescriptorsRequest);
    foreach ($descriptors->iterateAllElements() as $descriptor) {
        print($descriptor->getType() . PHP_EOL);
    }
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
resource_descriptors = client.list_monitored_resource_descriptors(name=project_name)
for descriptor in resource_descriptors:
    print(descriptor.type)

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

results = client.list_monitored_resource_descriptors name: project_name
results.each do |descriptor|
  p descriptor.type
end

如果遇到困难,请参阅排查 API 调用问题

获取资源描述符

要获取特定的受监控资源描述符,请使用 monitoredResourceDescriptors.get 方法。

要检索特定的受监控的资源描述符,您必须向 API 提供描述符的全名。全名由两部分组成:

  • projects/PROJECT_ID/monitoredResourceDescriptors 组成的前缀。
  • 用于标识受监控的资源描述符的 type 值,例如 gce_instance。如需详细了解 type 值,请参阅列出资源类型中的协议标签页。

以下是受监控的资源的全名示例:

projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance

协议

如需获取 gce_instance 资源类型的描述符,请执行以下操作:

  1. 打开 monitoredResourceDescriptors.get 参考页面。

  2. 在标有尝试此方法的窗格中,输入以下内容:

    • 名称projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance

      PROJECT_ID 替换为您的 Google Cloud 项目的 ID。

  3. 点击执行

以下示例响应显示了此受监控资源的描述符:

    {
      "type": "gce_instance",
      "displayName": "VM Instance",
      "description": "A virtual machine instance hosted in Compute Engine.",
      "labels": [
        {
          "key": "project_id",
          "description": "The identifier of the Google Cloud project associated with this resource, such as \"my-project\"."
        },
        {
          "key": "instance_id",
          "description": "The numeric VM instance identifier assigned by Compute Engine."
        },
        {
          "key": "zone",
          "description": "The Compute Engine zone in which the VM is running."
        }
      ],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance"
    }

如需采用 curl 命令、HTTP 请求或 JavaScript 格式查看请求,请在 API Explorer 中点击 全屏

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object GetMonitoredResource(string projectId, string resourceId)
{
    MetricServiceClient client = MetricServiceClient.Create();
    MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName(projectId, resourceId);
    var response = client.GetMonitoredResourceDescriptor(name);
    string resource = JObject.Parse($"{response}").ToString();
    Console.WriteLine($"{ resource }");
    return 0;
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import (
	"context"
	"fmt"
	"io"

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

// getMonitoredResource gets the descriptor for the given resourceType and
// prints information about it. resource should be of the form
// "projects/[PROJECT_ID]/monitoredResourceDescriptors/[RESOURCE_TYPE]".
func getMonitoredResource(w io.Writer, resource string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer c.Close()
	req := &monitoringpb.GetMonitoredResourceDescriptorRequest{
		Name: fmt.Sprintf(resource),
	}
	resp, err := c.GetMonitoredResourceDescriptor(ctx, req)
	if err != nil {
		return fmt.Errorf("could not get custom metric: %w", err)
	}

	fmt.Fprintf(w, "Name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
	fmt.Fprintf(w, "Type: %v\n", resp.GetType())
	fmt.Fprintf(w, "Labels:\n")
	for _, l := range resp.GetLabels() {
		fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
	}
	return nil
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

void getMonitoredResource(String resourceId) throws IOException {
  String projectId = System.getProperty("projectId");

  try (final MetricServiceClient client = MetricServiceClient.create();) {
    MonitoredResourceDescriptorName name =
        MonitoredResourceDescriptorName.of(projectId, resourceId);
    MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name);
    System.out.println("Retrieved Monitored Resource: " + gson.toJson(response));
  }
}

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 getMonitoredResourceDescriptor() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const resourceType = 'some_resource_type, e.g. cloudsql_database';

  const request = {
    name: client.projectMonitoredResourceDescriptorPath(
      projectId,
      resourceType
    ),
  };

  // Lists monitored resource descriptors
  const [descriptor] = await client.getMonitoredResourceDescriptor(request);

  console.log(`Name: ${descriptor.displayName}`);
  console.log(`Description: ${descriptor.description}`);
  console.log(`Type: ${descriptor.type}`);
  console.log('Labels:');
  descriptor.labels.forEach(label => {
    console.log(`  ${label.key} (${label.valueType}) - ${label.description}`);
  });
}
getMonitoredResourceDescriptor();

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

/**
 * Example:
 * ```
 * get_resource('your-project-id', 'gcs_bucket');
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $resourceType The resource type of the monitored resource.
 */
function get_resource($projectId, $resourceType)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $metricName = $metrics->monitoredResourceDescriptorName($projectId, $resourceType);
    $getMonitoredResourceDescriptorRequest = (new GetMonitoredResourceDescriptorRequest())
        ->setName($metricName);
    $resource = $metrics->getMonitoredResourceDescriptor($getMonitoredResourceDescriptorRequest);

    printf('Name: %s' . PHP_EOL, $resource->getName());
    printf('Type: %s' . PHP_EOL, $resource->getType());
    printf('Display Name: %s' . PHP_EOL, $resource->getDisplayName());
    printf('Description: %s' . PHP_EOL, $resource->getDescription());
    printf('Labels:' . PHP_EOL);
    foreach ($resource->getLabels() as $labels) {
        printf('  %s (%s) - %s' . PHP_EOL,
            $labels->getKey(),
            $labels->getValueType(),
            $labels->getDescription());
    }
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
resource_path = (
    f"projects/{project_id}/monitoredResourceDescriptors/{resource_type_name}"
)
descriptor = client.get_monitored_resource_descriptor(name=resource_path)
pprint.pprint(descriptor)

Ruby

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

# The resource type
# resource_type = "gce_instance"

client = Google::Cloud::Monitoring.metric_service
resource_path = client.monitored_resource_descriptor_path(
  project:                       project_id,
  monitored_resource_descriptor: resource_type
)

result = client.get_monitored_resource_descriptor name: resource_path
p result

如果遇到困难,请参阅排查 API 调用问题

后续步骤