Créer une métrique personnalisée

Explique comment créer une métrique personnalisée.

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 CreateMetric(string projectId,
            string metricType = "custom.googleapis.com/stores/daily_sales")
        {
            // Create client.
            MetricServiceClient metricServiceClient = MetricServiceClient.Create();

            // Prepare custom metric descriptor.
            MetricDescriptor metricDescriptor = new MetricDescriptor();
            metricDescriptor.DisplayName = "Daily Sales";
            metricDescriptor.Description = "Daily sales records from all branch stores.";
            metricDescriptor.MetricKind = MetricKind.Gauge;
            metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
            metricDescriptor.Type = metricType;
            metricDescriptor.Unit = "{USD}";
            LabelDescriptor labels = new LabelDescriptor();
            labels.Key = "store_id";
            labels.ValueType = LabelDescriptor.Types.ValueType.String;
            labels.Description = "The ID of the store.";
            metricDescriptor.Labels.Add(labels);
            CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
            {
                ProjectName = new ProjectName(projectId),
            };
            request.MetricDescriptor = metricDescriptor;
            // Make the request.
            MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
            Console.WriteLine("Done creating metric descriptor:");
            Console.WriteLine(JObject.Parse($"{response}").ToString());
            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"
	"google.golang.org/genproto/googleapis/api/label"
	"google.golang.org/genproto/googleapis/api/metric"
	metricpb "google.golang.org/genproto/googleapis/api/metric"
)

// createCustomMetric creates a custom metric specified by the metric type.
func createCustomMetric(w io.Writer, projectID, metricType string) (*metricpb.MetricDescriptor, error) {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return nil, err
	}
	defer c.Close()
	md := &metric.MetricDescriptor{
		Name: "Custom Metric",
		Type: metricType,
		Labels: []*label.LabelDescriptor{{
			Key:         "environment",
			ValueType:   label.LabelDescriptor_STRING,
			Description: "An arbitrary measurement",
		}},
		MetricKind:  metric.MetricDescriptor_GAUGE,
		ValueType:   metric.MetricDescriptor_INT64,
		Unit:        "s",
		Description: "An arbitrary measurement",
		DisplayName: "Custom Metric",
	}
	req := &monitoringpb.CreateMetricDescriptorRequest{
		Name:             "projects/" + projectID,
		MetricDescriptor: md,
	}
	m, err := c.CreateMetricDescriptor(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("could not create custom metric: %w", err)
	}

	fmt.Fprintf(w, "Created %s\n", m.GetName())
	return m, 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");

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ProjectName projectName = ProjectName.of(projectId);

  MetricDescriptor descriptor =
      MetricDescriptor.newBuilder()
          .setType(type)
          .addLabels(
              LabelDescriptor.newBuilder()
                  .setKey("store_id")
                  .setValueType(LabelDescriptor.ValueType.STRING))
          .setDescription("This is a simple example of a custom metric.")
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .build();

  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(projectName.toString())
          .setMetricDescriptor(descriptor)
          .build();

  descriptor = client.createMetricDescriptor(request);
  System.out.println("Created descriptor " + descriptor.getName());
}

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

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
async function createMetricDescriptor() {
  const request = {
    name: client.projectPath(projectId),
    metricDescriptor: {
      description: 'Daily sales records from all branch stores.',
      displayName: 'Daily Sales',
      type: 'custom.googleapis.com/stores/daily_sales',
      metricKind: 'GAUGE',
      valueType: 'DOUBLE',
      unit: '{USD}',
      labels: [
        {
          key: 'store_id',
          valueType: 'STRING',
          description: 'The ID of the store.',
        },
      ],
    },
  };

  // Creates a custom metric descriptor
  const [descriptor] = await client.createMetricDescriptor(request);
  console.log('Created custom Metric:\n');
  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}`);
  });
}
createMetricDescriptor();

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\Api\LabelDescriptor;
use Google\Api\MetricDescriptor;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\CreateMetricDescriptorRequest;

/**
 * Create a new metric in Stackdriver Monitoring.
 * Example:
 * ```
 * create_metric($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function create_metric($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;

    $descriptor = new MetricDescriptor();
    $descriptor->setDescription('Daily sales records from all branch stores.');
    $descriptor->setDisplayName('Daily Sales');
    $descriptor->setType('custom.googleapis.com/stores/daily_sales');
    $descriptor->setMetricKind(MetricDescriptor\MetricKind::GAUGE);
    $descriptor->setValueType(MetricDescriptor\ValueType::DOUBLE);
    $descriptor->setUnit('{USD}');
    $label = new LabelDescriptor();
    $label->setKey('store_id');
    $label->setValueType(LabelDescriptor\ValueType::STRING);
    $label->setDescription('The ID of the store.');
    $labels = [$label];
    $descriptor->setLabels($labels);
    $createMetricDescriptorRequest = (new CreateMetricDescriptorRequest())
        ->setName($projectName)
        ->setMetricDescriptor($descriptor);

    $descriptor = $metrics->createMetricDescriptor($createMetricDescriptorRequest);
    printf('Created a metric: ' . $descriptor->getName() . PHP_EOL);
}

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.api import label_pb2 as ga_label
from google.api import metric_pb2 as ga_metric
from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
descriptor = ga_metric.MetricDescriptor()
descriptor.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
descriptor.description = "This is a simple example of a custom metric."

labels = ga_label.LabelDescriptor()
labels.key = "TestLabel"
labels.value_type = ga_label.LabelDescriptor.ValueType.STRING
labels.description = "This is a test label"
descriptor.labels.append(labels)

descriptor = client.create_metric_descriptor(
    name=project_name, metric_descriptor=descriptor
)
print("Created {}.".format(descriptor.name))

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
project_name = client.project_path project: project_id

descriptor = Google::Api::MetricDescriptor.new(
  type:        metric_type,
  metric_kind: Google::Api::MetricDescriptor::MetricKind::GAUGE,
  value_type:  Google::Api::MetricDescriptor::ValueType::DOUBLE,
  description: "This is a simple example of a custom metric."
)

result = client.create_metric_descriptor name:              project_name,
                                         metric_descriptor: descriptor
p "Created #{result.name}"
p result

Étapes suivantes

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