列出指标和资源类型

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

  • Trusted Cloud by S3NS提供的内置指标类型。这些指标类型可帮助您设计用户定义的指标。您还可以在文档中找到这些指标的相关信息;请参阅指标列表
  • 可用于您的项目的受监控的资源类型。您还可以在文档中找到这些资源的相关信息;请参阅受监控的资源列表
  • 此文档介绍了调用所述 API 方法的几种方式。

    准备工作

    列出指标描述符

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

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

    列出指标类型

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

    C#

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

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    
    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    gem "google-cloud-monitoring"
    require "google/cloud/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
    

    C#

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

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    
    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    from google.cloud import monitoring_v3
    
    client = monitoring_v3.MetricServiceClient()
    descriptor = client.get_metric_descriptor(name=metric_name)
    pprint.pprint(descriptor)

    Ruby

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

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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
    
    descriptor = client.get_metric_descriptor name: metric_name
    p descriptor

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

    列出受监控的资源

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

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

    列出资源类型

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

    C#

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

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

            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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    
    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    gem "google-cloud-monitoring"
    require "google/cloud/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
    

    C#

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

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    
    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    // 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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    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 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

    在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

    # 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 调用问题

    后续步骤

    • 如需了解如何使用 Cloud Monitoring API 读取时序数据,请参阅检索时序数据