指標とリソースタイプを一覧表示する

このドキュメントでは、Cloud Monitoring API を使用して、のリストまたは説明を取得する方法について説明します。

  • プロジェクトで定義されたユーザー定義指標タイプ。
  • プロジェクトで時系列データを使用するサードパーティ指標タイプ。BindPlane によって生成される指標は、サードパーティの指標の例です。BindPlane の指標には workload.googleapis.com/3rd-party-app-name/ という接頭辞が付いています。サポートされているサードパーティ アプリケーション指標の完全なリストについては、BindPlane のソースのドキュメントをご覧ください。
  • Google Cloud が提供する組み込み指標タイプ。これらの指標タイプは、ユーザー定義指標を設計する際に有用です。これらの指標の詳細については、ドキュメントの指標の一覧もご覧ください。
  • プロジェクトで使用可能なモニタリング対象リソース タイプ。これらのリソースに関する情報は、ドキュメントでも確認できます。モニタリング対象リソース リストをご覧ください。
このドキュメントで説明する API メソッドを使用する方法はいくつかあります。

  • コードを記述せずにこれらのメソッドを実行するには、このページの [プロトコル] タブにある例からフォームベースの API Explorer を使用します(このツールの詳細については、API Explorer をご覧ください)。

  • 選択したプログラミング言語からこれらのメソッドを使用する方法については、このページの実行可能なコードサンプルをご覧ください。

始める前に

指標記述子を一覧表示

指標記述子は、指標を定義するスキーマです。興味のある指標の詳細を見つけるには、利用可能な指標 記述子を閲覧します。

  • 組み込み指標: 既存のプロジェクトに対して API リクエストを発行することや、指標リストのドキュメントを使用することができます。
  • ユーザー定義指標と外部指標: ユーザー定義指標が定義されているプロジェクトや、指標の時系列データが存在するプロジェクトに、API リクエストを発行する必要があります。

指標タイプの命名方法について詳しくは、命名規則をご覧ください。

指標タイプを一覧表示する

現在の指標記述子の一覧を取得するには、metricDescriptors.list メソッドを使用します。返された指標タイプのセットを絞り込むには、フィルタを使用します。 どの指標タイプを検索すべきか判断できない場合は、値の型と指標の種類をご覧ください。

プロトコル

  1. metricDescriptors.list リファレンス ページを開きます。

  2. [Try this method] ペインに、次のように入力します。

    • 名前: projects/PROJECT_IDPROJECT_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 として表示するには、API Explorer で [Full screen] をクリックします。

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 呼び出しのトラブルシューティングをご覧ください。

指標記述子を取得する

1 つの指標タイプに関する情報を取得するには、metricDescriptors.get メソッドを使用します。このメソッドは、指標記述子を返します。

特定の指標記述子を取得するには、API に対して指標の完全な名前を指定する必要があります。フルネームは、次の 2 つのコンポーネントで構成されます。

  • 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. [Try this method] ペインに、次のように入力します。

    • 名前: 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 として表示するには、API Explorer で [Full screen] をクリックします。

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. [Try this method] ペインに、次のように入力します。

    • 名前: projects/PROJECT_IDPROJECT_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 で [Full screen] をクリックします。

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 に対して指定する必要があります。フルネームは、次の 2 つのコンポーネントで構成されます。

  • projects/PROJECT_ID/monitoredResourceDescriptors で構成される接頭辞。
  • モニタリング対象リソース記述子を識別する type 値(例: gce_instance)。type 値の詳細については、リソースタイプの一覧表示の [プロトコル] タブをご覧ください。

モニタリング対象リソースのフルネームの例を次に示します。

projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance

プロトコル

gce_instance リソースタイプの記述子を取得するには、次の操作を行います。

  1. monitoredResourceDescriptors.get リファレンス ページを開きます。

  2. [Try this method] ペインに、次のように入力します。

    • 名前: 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 で [Full screen] をクリックします。

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 呼び出しのトラブルシューティングをご覧ください。

次のステップ