측정항목 및 리소스 유형 나열

이 문서에서는 Cloud Monitoring API를 사용하여 다음 항목들에 대한 목록 또는 설명을 확인하는 방법을 보여줍니다.

  • 프로젝트에 정의된 사용자 정의 측정항목 유형.
  • 프로젝트에서 시계열 데이터가 있는 서드 파티 측정항목 유형. 서드 파티 측정항목의 예시로 BindPlane에서 생성된 측정항목이 있습니다. BindPlane 측정항목에는 workload.googleapis.com/3rd-party-app-name/ 프리픽스가 포함됩니다. 지원되는 타사 애플리케이션 측정항목의 전체 목록은 BindPlane 소스 문서를 참조하세요.
  • Google Cloud에서 제공되는 기본 제공 측정항목 유형. 이러한 측정항목 유형은 사용자 정의 측정항목을 설계하는 데 도움이 될 수 있습니다. 또한 문서에서 이러한 측정항목에 대한 정보를 찾을 수도 있습니다. 측정항목 목록을 참조하세요.
  • 프로젝트에 제공되는 모니터링되는 리소스 유형. 또한 문서에서 이러한 리소스에 대한 정보를 찾을 수도 있습니다 모니터링되는 리소스 목록을 참조하세요.
이 문서에서 설명하는 API 메서드를 사용하는 방법에는 여러 가지가 있습니다.

  • 코드를 작성하지 않고 메서드를 실행하기 위해 이 페이지의 프로토콜 탭 예에서는 양식 기반 API 탐색기를 사용합니다. (이 도구에 대한 자세한 내용은 API 탐색기를 참조하세요.)

  • 선택한 프로그래밍 언어로 메서드를 사용하는 방법을 알아보려면 이 페이지의 실행 가능한 코드 샘플을 참조하세요.

시작하기 전에

측정항목 설명자 나열

측정항목 설명자는 측정항목을 정의하는 스키마입니다. 관심 있는 측정항목에 대한 세부정보를 찾으려면 제공되는 측정항목 설명을 찾아보세요.

  • 기본 제공 측정항목: 기존 프로젝트에 API 요청을 수행하거나 측정항목 목록 문서를 사용할 수 있습니다.
  • 사용자 정의 및 외부 측정항목: 사용자 정의 측정항목이 정의되었거나 측정항목에 대한 시계열 데이터가 존재하는 프로젝트에 API 요청을 수행해야 합니다.

측정항목 유형의 이름을 지정하는 방법에 대한 자세한 내용은 이름 지정 규칙을 참조하세요.

측정항목 유형 나열

현재 측정항목 설명 목록을 가져오려면 metricDescriptors.list 메서드를 사용합니다. 반환되는 측정항목 유형의 범위를 좁히려면 필터를 사용합니다. 검색할 측정항목 유형을 결정하기 위해서는 값 유형 및 측정항목 종류를 참조하세요.

프로토콜

  1. metricDescriptors.list 참조 페이지를 엽니다.

  2. 이 메서드 사용해 보기 라벨이 지정된 창에 다음을 입력합니다.

    • name: projects/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로 보려면 API 탐색기에서 전체 화면을 클릭합니다.

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로 보려면 API 탐색기에서 전체 화면을 클릭합니다.

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. 이 메서드 사용해 보기 라벨이 지정된 창에 다음을 입력합니다.

    • name: projects/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 탐색기에서 전체 화면을 클릭합니다.

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 탐색기에서 전체 화면을 클릭합니다.

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 호출 문제 해결을 참조하세요.

다음 단계

  • Cloud Monitoring API를 사용하여 시계열 데이터를 읽는 방법에 대한 자세한 내용은 시계열 데이터 검색을 참조하세요.
  • 사용자 정의 측정항목과 함께 사용할 수 있는 모니터링 리소스 유형의 목록은 모니터링 리소스 유형 선택을 참조하세요.