列出指標和資源類型

本文說明如何使用 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 呼叫問題」。

    後續步驟