Obtenir un descripteur de métrique

Explique comment obtenir les détails d'un descripteur de métrique.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Go

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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.
func getMetricDescriptor(w io.Writer, projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer c.Close()
	req := &monitoringpb.GetMetricDescriptorRequest{
		Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", projectID, metricType),
	}
	resp, err := c.GetMetricDescriptor(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, "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 := range resp.GetLabels() {
		fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
	}
	return nil
}

Java

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

MetricDescriptorName descriptorName = MetricDescriptorName.of(projectId, type);

try (final MetricServiceClient client = MetricServiceClient.create();) {
  MetricDescriptor response = client.getMetricDescriptor(descriptorName);

  System.out.println("Printing metrics descriptor: " + response);
}

Node.js

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

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

async function getMetricDescriptor() {
  /**
   * 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.projectMetricDescriptorPath(projectId, metricId),
  };

  // Retrieves a metric descriptor
  const [descriptor] = await client.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

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from google.cloud import monitoring_v3

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

Ruby

Pour vous authentifier auprès de Monitoring, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

# 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_descriptor name: metric_name
p descriptor

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.