List metric descriptors

Demonstrates how to list available metric descriptors.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# 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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.