Get a monitored resource

Demonstrates how to get the details of a monitored resource.

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

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

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

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

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

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

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

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()
resource_path = (
    f"projects/{project_id}/monitoredResourceDescriptors/{resource_type_name}"
)
descriptor = client.get_monitored_resource_descriptor(name=resource_path)
pprint.pprint(descriptor)

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"

# 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

What's next

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