Browsing Metric and Resource Types

This page explains how to use the Monitoring API to do the following:

  • Get a list or description of your custom metric types.
  • Get a list or description of built-in metric types, which can help you design your custom metrics. This list also appears in the documentation; see Metrics List.
  • Get a list or description of the available monitored resource types, which you can use to label your custom metrics' time series data. This list also appears in the documentation; see Monitored Resource List.

For an introduction to these concepts, see Metrics, Time Series, and Resources.

This page describes the metricDescriptors.list and get methods, and the monitoredResourceDescriptors.list and get methods. There are several ways to use these methods:

  • To run the methods without writing any code, the examples in the PROTOCOL tabs on this page use the forms-based API Explorer. (See API Explorer for more information on this tool.)

  • To learn how to use the methods from selected programming languages, see the runnable code samples on this page.

Workspace not required

Except when working with custom metrics, you can use any existing project in metricDescriptors.list and get invocations, even if the project is not in a Workspace. If you are working with custom metrics, then you must specify the project where the custom metrics are defined.

You can also use any existing project with the monitoredResourceDescriptors.list and get methods.

Listing metric descriptors

Metric descriptors are the schemas that define built-in and custom metrics. By browsing the available metric descriptors, you can find out details about the metrics you're interested in.

There are presently over 900 built-in metrics; see the complete Metrics List for reference.

For more information on how metric types are named, see Naming rules.

Example: Listing metric types

To get a current list of metric types, use the metricDescriptors.list method. Use a filter to narrow the set of metric types that are returned. See Metric types for help deciding which metric type names to search for.

Protocol

The following are sample parameters to metricDescriptors.list for returning Compute Engine metrics:

  • name: projects/[PROJECT_ID]
  • filter: metric.type = starts_with("compute.googleapis.com")
  • fields: metricDescriptors.type,metricDescriptors.displayName

Try It!

Before clicking the Execute button, change [PROJECT_ID] to a valid ID.

The following sample output shows three of the many Compute Engine metrics that match the filter:

"metricDescriptors": [
  {
   "displayName": "Dropped bytes",
   "type": "compute.googleapis.com/firewall/dropped_bytes_count"
  },
  {
   "displayName": "Dropped packets",
   "type": "compute.googleapis.com/firewall/dropped_packets_count"
  },
  {
   "displayName": "Reserved cores.",
   "type": "compute.googleapis.com/instance/cpu/reserved_cores"
  },
  ...
]

The type value here identifies the metric descriptor, for example, compute.googleapis.com/firewall/dropped_packets_count. This value is sometimes also called the “metric type^” or the “metric type name”.

C#

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

// getCustomMetric reads the custom metric created.
func getCustomMetric(projectID, metricType string) (*metric.MetricDescriptor, error) {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return nil, err
	}
	req := &monitoringpb.GetMetricDescriptorRequest{
		Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", projectID, metricType),
	}
	resp, err := c.GetMetricDescriptor(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("could not get custom metric: %v", err)
	}

	log.Printf("getCustomMetric: %s\n", formatResource(resp))
	return resp, nil
}

Java

// Your Google Cloud Platform project ID
String projectId = System.getProperty("projectId");

final MetricServiceClient client = MetricServiceClient.create();
ProjectName name = ProjectName.of(projectId);

ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest
    .newBuilder()
    .setName(name.toString())
    .build();
ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);

System.out.println("Listing descriptors: ");

for (MetricDescriptor d : response.iterateAll()) {
  System.out.println(d.getName() + " " + d.getDisplayName());
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  name: client.projectPath(projectId),
};

// Lists metric descriptors
client
  .listMetricDescriptors(request)
  .then(results => {
    const descriptors = results[0];

    console.log('Metric Descriptors:');
    descriptors.forEach(descriptor => console.log(descriptor.name));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;

/**
 * Example:
 * ```
 * list_descriptors($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function list_descriptors($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = $metrics->projectName($projectId);
    $descriptors = $metrics->listMetricDescriptors($projectName);

    printf('Metric Descriptors:' . PHP_EOL);
    foreach ($descriptors->iterateAllElements() as $descriptor) {
        printf($descriptor->getName() . PHP_EOL);
    }
}

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
for descriptor in client.list_metric_descriptors(project_name):
    print(descriptor.type)

See Troubleshooting API calls if you have difficulty.

Example: Getting metric descriptors

To get more details about a metric type, retrieve the full metric descriptor using the metricDescriptors.get method.

To retrieve a specific metric descriptor, you need the full name of the descriptor. This value is constructed from two components:

  • A prefix consisting of projects/[PROJECT_ID]/metricDescriptors.
  • The type value that identifies the metric descriptor, for example, compute.googleapis.com/firewall/dropped_packets_count. See the PROTOCOL tab in Example: Listing metric types for more on the type value.

Example: projects/[PROJECT_ID]/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count.

Protocol

To get the details of Compute Engine's /firewall/dropped_packets_count metric, use the following parameter to metricDescriptors.get:

  • name: projects/[PROJECT_ID]/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count

Try It!

Before clicking the Execute button, change [PROJECT_ID] to a valid ID.

The following sample response shows the metric's descriptor:

{
  "type": "compute.googleapis.com/firewall/dropped_packets_count",
  "name": "projects/[PROJECT_ID]/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count",
  "description": "Delta count of incoming packets dropped by the firewall.",
  "displayName": "Dropped packets",
  "labels": [
   {
    "key": "instance_name",
    "description": "The name of the VM instance."
   }
  ],
  "metricKind": "DELTA",
  "valueType": "INT64",
  "unit": "1"
}

C#

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

Java

// Your Google Cloud Platform project ID
String projectId = System.getProperty("projectId");

final MetricServiceClient client = MetricServiceClient.create();
MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.of(projectId, type);
MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name);

System.out.println("Printing monitored resource descriptor: ");
System.out.println(response);

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * 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.metricDescriptorPath(projectId, metricId),
};

// Retrieves a metric descriptor
client
  .getMetricDescriptor(request)
  .then(results => {
    const descriptor = results[0];

    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}`
      );
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;

/**
 * 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);
    $descriptor = $metrics->getMetricDescriptor($metricName);

    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

client = monitoring_v3.MetricServiceClient()
descriptor = client.get_metric_descriptor(metric_name)
pprint.pprint(descriptor)

See Troubleshooting API calls if you have difficulty.

Listing monitored resources

Monitored resources are cloud entities that can be monitored. By browsing the existing monitored resource types, you can find the kinds of entities that have metrics.

There are presently about 100 different monitored resource descriptors; see the Monitored Resource List for the full set.

For an introduction to metric descriptors and monitored resources, see Metrics, Time Series, and Resources.

You can use any existing project in monitoredResourceDescriptors.list and get invocations, even if the project is not in a Workspace.

Example: Listing resource types

To get a current list of monitored resource types from the Monitoring API, use the monitoredResourceDescriptors.list method and supply your project ID.

Protocol

To get a current list of monitored resource types, use monitoredResourceDescriptors.list with the following sample parameters:

  • name: projects/[PROJECT_ID]
  • fields: resourceDescriptors.type

Try It!

Before clicking the Execute button, change [PROJECT_ID] to a valid ID.

The following sample response shows some of the returned monitored resource types:

{
 "resourceDescriptors": [
  {
   "type": "api"
  },
  {
   "type": "aws_cloudfront_distribution"
  },
  {
   "type": "aws_dynamodb_table"
  },
  {
   "type": "aws_ebs_volume"
  },
  ...
}

C#

        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 != null)
            {
                foreach (MonitoredResourceDescriptor resource in resources.Take(10))
                {
                    Console.WriteLine($"{resource.Name}: {resource.DisplayName}");
                }
            }
            else { Console.WriteLine("No resources found."); }
            return 0;
        }

Java

// Your Google Cloud Platform project ID
String projectId = System.getProperty("projectId");

final MetricServiceClient client = MetricServiceClient.create();
ProjectName name = ProjectName.of(projectId);

ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest
    .newBuilder()
    .setName(name.toString())
    .build();

System.out.println("Listing monitored resource descriptors: ");

ListMonitoredResourceDescriptorsPagedResponse response = client
    .listMonitoredResourceDescriptors(request);

for (MonitoredResourceDescriptor d : response.iterateAll()) {
  System.out.println(d.getType());
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * 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
client
  .listMonitoredResourceDescriptors(request)
  .then(results => {
    const descriptors = results[0];

    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();
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
resource_descriptors = (
    client.list_monitored_resource_descriptors(project_name))
for descriptor in resource_descriptors:
    print(descriptor.type)

See Troubleshooting API calls if you have difficulty.

Getting resource descriptors

To get more details about a monitored resource types, retrieve the full descriptor using the monitoredResourceDescriptors.get method method.

To retrieve a specific monitored resource descriptor, you need the full name of the descriptor. This value is constructed from two components:

  • A prefix consisting of projects/[PROJECT_ID]/monitoredResourceDescriptors.
  • The type value that identifies the metric descriptor, for example, gce_instance. See the PROTOCOL tab in Example: Listing resource types for more on the type value.

Example: projects/[PROJECT_ID]/monitoredResourceDescriptors/gce_instance.

Protocol

To get the details of the gce_instance resource type, use the following parameter to monitoredResourceDescriptors.get method:

  • name: projects/[PROJECT_ID]/monitoredResourceDescriptors/gce_instance

Try It!

Before clicking the Execute button, change [PROJECT_ID] to a valid ID.

The following sample response shows the descriptor for this monitored resource:

{
  "type": "gce_instance",
  "displayName": "G​C​E VM Instance",
  "description": "A virtual machine instance hosted in Google Compute Engine (G​C​E).",
  "labels": [
    {
      "key": "project_id",
      "description": "The identifier of the GCP 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"
}

C#

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

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

/**
 * 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.monitoredResourceDescriptorPath(projectId, resourceType),
};

// Lists monitored resource descriptors
client
  .getMonitoredResourceDescriptor(request)
  .then(results => {
    const descriptor = results[0];

    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}`
      );
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

client = monitoring_v3.MetricServiceClient()
resource_path = client.monitored_resource_descriptor_path(
    project_id, resource_type_name)
pprint.pprint(client.get_monitored_resource_descriptor(resource_path))

See Troubleshooting API calls if you have difficulty.

Finding resources

Monitored resource objects are included in time series data. You can usually guess which metrics include monitored resources of specific types. For example, if you want to see a gce_instance monitored resource, look at time series data from a metric like compute.googleapils.com/instance/cpu/utilization. After you've identified a likely metric time series, see Reading metric data.

Was this page helpful? Let us know how we did:

Send feedback about...

Stackdriver Monitoring