List metric and resource types
Stay organized with collections
Save and categorize content based on your preferences.
This document explains how to use the Cloud Monitoring API to get lists or descriptions of the following:
- User-defined metric types defined in your project.
- Third-party metric types with time-series data in your project.
Metrics generated by Bindplane
are examples of third-party metrics. Bindplane metrics
have a prefix of
workload.googleapis.com/3rd-party-app-name/. For a full list of supported third-party application metrics, see the Bindplane Sources documentation. - Built-in metric types provided by Google Cloud. These metric types can help you design your user-defined metrics. You can also find information about these metrics in the documentation; see Metrics list.
- Monitored resource types available to your project. You can also find information about these resources in the documentation; see Monitored resource list.
To run the methods without writing any code, the examples in the Protocol tabs on this page use the forms-based APIs Explorer. (See APIs Explorer for more information about this tool.)
To learn how to use the methods from selected programming languages, see the runnable code samples on this page.
Before you begin
- For an introduction to metrics and monitored resources, see Metrics, time series, and resources.
List metric descriptors
Metric descriptors are the schemas that define metrics. To find details about the metrics you're interested in, browse the available metric descriptors:- Built-in metrics: You can issue API requests to any existing project, or you can use Metrics lists documentation.
- User-defined and external metrics: You must issue the API request to a project where the user-defined metric is defined or where time-series data for the metric exists.
For more information on how metric types are named, see Naming conventions.
List metric types
To get a current list of metric descriptors, use the
metricDescriptors.list method.
To narrow the set of metric types that are returned, use a filter.
For help deciding which metric types to search for, see
Value types and metric kinds.
Protocol
Open the
metricDescriptors.listreference page.In the pane labeled Try this method, enter the following:
- name:
projects/PROJECT_ID. ReplacePROJECT_IDwith the ID of your Google Cloud project. - filter:
metric.type = starts_with("compute.googleapis.com")
- name:
Click Execute.
The following sample response shows some of the retrieved metric descriptors:
"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",
},
...
]
The type value in each descriptor 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”.
To view the request as a curl command, as an
HTTP request, or in JavaScript, click fullscreen Full screen
in APIs Explorer.
C#
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
publicstaticobjectListMetrics(stringprojectId)
{
MetricServiceClientclient=MetricServiceClient.Create();
ProjectNameprojectName=newProjectName(projectId);
PagedEnumerable<ListMetricDescriptorsResponse,MetricDescriptor>metrics=client.ListMetricDescriptors(projectName);
foreach(MetricDescriptormetricinmetrics)
{
Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
}
return0;
}
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.
funclistMetrics(wio.Writer,projectIDstring)error{
ctx:=context.Background()
c,err:=monitoring.NewMetricClient(ctx)
iferr!=nil{
returnerr
}
deferc.Close()
req:=&monitoringpb.ListMetricDescriptorsRequest{
Name:"projects/"+projectID,
}
iter:=c.ListMetricDescriptors(ctx,req)
for{
resp,err:=iter.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnfmt.Errorf("Could not list metrics: %w",err)
}
fmt.Fprintf(w,"%v\n",resp.GetType())
}
fmt.Fprintln(w,"Done")
returnnil
}
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
StringprojectId=System.getProperty("projectId");
ProjectNamename=ProjectName.of(projectId);
ListMetricDescriptorsRequestrequest=
ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();
// Instantiates a client
try(finalMetricServiceClientclient=MetricServiceClient.create();){
ListMetricDescriptorsPagedResponseresponse=client.listMetricDescriptors(request);
System.out.println("Listing descriptors: ");
for(MetricDescriptord: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
constmonitoring=require('@google-cloud/monitoring');
// Creates a client
constclient=newmonitoring.MetricServiceClient ();
asyncfunctionlistMetricDescriptors(){
/**
* TODO(developer): Uncomment and edit the following lines of code.
*/
// const projectId = 'YOUR_PROJECT_ID';
constrequest={
name:client.projectPath(projectId),
};
// Lists metric descriptors
const[descriptors]=awaitclient.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.
fromgoogle.cloudimport 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.
gem"google-cloud-monitoring"
require"google/cloud/monitoring"
# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"
client=Google::Cloud::Monitoring .metric_service
project_name=client.project_pathproject:project_id
results=client.list_metric_descriptorsname:project_name
results.eachdo|descriptor|
pdescriptor.type
endIf you have difficulty, see Troubleshooting API calls.
Get metric descriptors
To get information about a single metric type, use the
metricDescriptors.get method.
This method returns a metric descriptor.
To retrieve a specific metric descriptor, you must provide the full name of the metric to the API. The full name is constructed from two components:
- A prefix consisting of
projects/PROJECT_ID/metricDescriptors. - The
typevalue that identifies the metric descriptor, for example,compute.googleapis.com/firewall/dropped_packets_count. See the Protocol tab in List metric types for more on thetypevalue.
The following is an example of the full name of a metric:
projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count
Protocol
To get the descriptor for the Compute Engine /firewall/dropped_packets_count
metric, do the following:
Open the
metricDescriptors.listreference page.In the pane labeled Try this method, enter the following:
name:
projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_countReplace
PROJECT_IDwith the ID of your Google Cloud project.
Click Execute.
The following sample response shows the metric's descriptor:
{
"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",
}
To view the request as a curl command, as an
HTTP request, or in JavaScript, click fullscreen Full screen
in APIs Explorer.
C#
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
publicstaticobjectGetMetricDetails(stringprojectId,stringmetricType)
{
MetricServiceClientclient=MetricServiceClient.Create();
MetricDescriptorNamename=newMetricDescriptorName(projectId,metricType);
try
{
varresponse=client.GetMetricDescriptor(name);
stringmetric=JObject.Parse($"{response}").ToString();
Console.WriteLine($"{ metric }");
}
catch(Grpc.Core.RpcExceptionex)
when(ex.Status.StatusCode==Grpc.Core.StatusCode.NotFound)
{}
return0;
}
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"
)
// 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.
funcgetMetricDescriptor(wio.Writer,projectID,metricTypestring)error{
ctx:=context.Background()
c,err:=monitoring.NewMetricClient(ctx)
iferr!=nil{
returnfmt.Errorf("NewMetricClient: %w",err)
}
deferc.Close()
req:=&monitoringpb.GetMetricDescriptorRequest{
Name:fmt.Sprintf("projects/%s/metricDescriptors/%s",projectID,metricType),
}
resp,err:=c.GetMetricDescriptor(ctx,req)
iferr!=nil{
returnfmt.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:=rangeresp.GetLabels(){
fmt.Fprintf(w,"\t%s (%s) - %s",l.GetKey(),l.GetValueType(),l.GetDescription())
}
returnnil
}
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
finalStringprojectId=System.getProperty("projectId");
MetricDescriptorNamedescriptorName=MetricDescriptorName.of(projectId,type);
try(finalMetricServiceClientclient=MetricServiceClient.create();){
MetricDescriptorresponse=client.getMetricDescriptor(descriptorName);
System.out.println("Printing metrics descriptor: "+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
constmonitoring=require('@google-cloud/monitoring');
// Creates a client
constclient=newmonitoring.MetricServiceClient ();
asyncfunctiongetMetricDescriptor(){
/**
* TODO(developer): Uncomment and edit the following lines of code.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const metricId = 'custom.googleapis.com/your/id';
constrequest={
name:client.projectMetricDescriptorPath (projectId,metricId),
};
// Retrieves a metric descriptor
const[descriptor]=awaitclient.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
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\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
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
fromgoogle.cloudimport monitoring_v3
client = monitoring_v3 .MetricServiceClient ()
descriptor = client.get_metric_descriptor (name=metric_name)
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.
gem"google-cloud-monitoring"
require"google/cloud/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_descriptorname:metric_name
pdescriptorIf you have difficulty, see Troubleshooting API calls.
List monitored resources
Monitored resources are cloud entities that can be monitored. To find the kinds of entities that have metrics, browse the list of monitored resource types.
To get information about monitored resources, you can issue API requests to any existing project, or you can use the Monitored resource list documentation.
List 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
Open the
monitoredResourceDescriptors.listreference page.In the pane labeled Try this method, enter the following:
- name:
projects/PROJECT_ID. ReplacePROJECT_IDwith the ID of your Google Cloud project.
- name:
Click Execute.
The following sample response shows some of the returned monitored resource types:
{
"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",
},
To view the request as a curl command, as an
HTTP request, or in JavaScript, click fullscreen Full screen
in APIs Explorer.
C#
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
publicstaticobjectListMonitoredResources(stringprojectId)
{
Console.WriteLine("Starting to List Monitored Resources...");
MetricServiceClientclient=MetricServiceClient.Create();
ProjectNameprojectName=newProjectName(projectId);
PagedEnumerable<ListMonitoredResourceDescriptorsResponse,MonitoredResourceDescriptor>
resources=client.ListMonitoredResourceDescriptors(projectName);
if(resources.Any())
{
foreach(MonitoredResourceDescriptorresourceinresources.Take(10))
{
Console.WriteLine($"{resource.Name}: {resource.DisplayName}");
}
}
else
{
Console.WriteLine("No resources found.");
}
return0;
}
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.
funclistMonitoredResources(wio.Writer,projectIDstring)error{
ctx:=context.Background()
c,err:=monitoring.NewMetricClient(ctx)
iferr!=nil{
returnerr
}
deferc.Close()
req:=&monitoringpb.ListMonitoredResourceDescriptorsRequest{
Name:"projects/"+projectID,
}
iter:=c.ListMonitoredResourceDescriptors(ctx,req)
for{
resp,err:=iter.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnfmt.Errorf("Could not list time series: %w",err)
}
fmt.Fprintf(w,"%v\n",resp)
}
fmt.Fprintln(w,"Done")
returnnil
}
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
StringprojectId=System.getProperty("projectId");
ProjectNamename=ProjectName.of(projectId);
ListMonitoredResourceDescriptorsRequestrequest=
ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build();
System.out.println("Listing monitored resource descriptors: ");
// Instantiates a client
try(finalMetricServiceClientclient=MetricServiceClient.create();){
ListMonitoredResourceDescriptorsPagedResponseresponse=
client.listMonitoredResourceDescriptors(request);
for(MonitoredResourceDescriptord: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
constmonitoring=require('@google-cloud/monitoring');
// Creates a client
constclient=newmonitoring.MetricServiceClient ();
asyncfunctionlistMonitoredResourceDescriptors(){
/**
* TODO(developer): Uncomment and edit the following lines of code.
*/
// const projectId = 'YOUR_PROJECT_ID';
constrequest={
name:client.projectPath(projectId),
};
// Lists monitored resource descriptors
const[descriptors]=
awaitclient.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.
fromgoogle.cloudimport 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.
gem"google-cloud-monitoring"
require"google/cloud/monitoring"
# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"
client=Google::Cloud::Monitoring .metric_service
project_name=client.project_pathproject:project_id
results=client.list_monitored_resource_descriptorsname:project_name
results.eachdo|descriptor|
pdescriptor.type
endIf you have difficulty, see Troubleshooting API calls.
Getting resource descriptors
To get a specific monitored-resource descriptor, use the
monitoredResourceDescriptors.get method.
To retrieve a specific monitored-resource descriptor, you must provide the full name of the descriptor to the API. The full name is constructed from two components:
- A prefix consisting of
projects/PROJECT_ID/monitoredResourceDescriptors. - The
typevalue that identifies the monitored-resource descriptor, for example,gce_instance. See the Protocol tab in List resource types for more on thetypevalue.
The following is an example of the full name of a monitored resource:
projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance
Protocol
To get the descriptor for the gce_instance resource type, do the following:
Open the
monitoredResourceDescriptors.getreference page.In the pane labeled Try this method, enter the following:
name:
projects/PROJECT_ID/monitoredResourceDescriptors/gce_instanceReplace
PROJECT_IDwith the ID of your Google Cloud project.
Click Execute.
The following sample response shows the descriptor for this monitored resource:
{
"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"
}
To view the request as a curl command, as an
HTTP request, or in JavaScript, click fullscreen Full screen
in APIs Explorer.
C#
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
publicstaticobjectGetMonitoredResource(stringprojectId,stringresourceId)
{
MetricServiceClientclient=MetricServiceClient.Create();
MonitoredResourceDescriptorNamename=newMonitoredResourceDescriptorName(projectId,resourceId);
varresponse=client.GetMonitoredResourceDescriptor(name);
stringresource=JObject.Parse($"{response}").ToString();
Console.WriteLine($"{ resource }");
return0;
}
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]".
funcgetMonitoredResource(wio.Writer,resourcestring)error{
ctx:=context.Background()
c,err:=monitoring.NewMetricClient(ctx)
iferr!=nil{
returnfmt.Errorf("NewMetricClient: %w",err)
}
deferc.Close()
req:=&monitoringpb.GetMonitoredResourceDescriptorRequest{
Name:resource,
}
resp,err:=c.GetMonitoredResourceDescriptor(ctx,req)
iferr!=nil{
returnfmt.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:=rangeresp.GetLabels(){
fmt.Fprintf(w,"\t%s (%s) - %s",l.GetKey(),l.GetValueType(),l.GetDescription())
}
returnnil
}
Java
To authenticate to Monitoring, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
voidgetMonitoredResource(StringresourceId)throwsIOException{
StringprojectId=System.getProperty("projectId");
try(finalMetricServiceClientclient=MetricServiceClient.create();){
MonitoredResourceDescriptorNamename=
MonitoredResourceDescriptorName.of(projectId,resourceId);
MonitoredResourceDescriptorresponse=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
constmonitoring=require('@google-cloud/monitoring');
// Creates a client
constclient=newmonitoring.MetricServiceClient ();
asyncfunctiongetMonitoredResourceDescriptor(){
/**
* TODO(developer): Uncomment and edit the following lines of code.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const resourceType = 'some_resource_type, e.g. cloudsql_database';
constrequest={
name:client.projectMonitoredResourceDescriptorPath (
projectId,
resourceType
),
};
// Lists monitored resource descriptors
const[descriptor]=awaitclient.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.
fromgoogle.cloudimport 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_descriptorname:resource_path
presultIf you have difficulty, see Troubleshooting API calls.
What's next
- For information about how to use the Cloud Monitoring API to read time-series data, see Retrieve time-series data.
- For a list of monitored-resource types available for your use with user-defined metrics, see Choose a monitored-resource type.