List monitored resources

Demonstrates how to list monitored resources.

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

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"
)

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

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);

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

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

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

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}"
resource_descriptors = client.list_monitored_resource_descriptors(name=project_name)
for descriptor in resource_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_monitored_resource_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.