À utiliser PutMetricData avec un AWS SDK ou CLI - Exemples de code de l'AWS SDK

D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

À utiliser PutMetricData avec un AWS SDK ou CLI

Les exemples de code suivants montrent comment utiliserPutMetricData.

Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans les exemples de code suivants :

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/// <summary> /// Add some metric data using a call to a wrapper class. /// </summary> /// <param name="customMetricName">The metric name.</param> /// <param name="customMetricNamespace">The metric namespace.</param> /// <returns></returns> private static async Task<List<MetricDatum>> PutRandomMetricData(string customMetricName, string customMetricNamespace) { List<MetricDatum> customData = new List<MetricDatum>(); Random rnd = new Random(); // Add 10 random values up to 100, starting with a timestamp 15 minutes in the past. var utcNowMinus15 = DateTime.UtcNow.AddMinutes(-15); for (int i = 0; i < 10; i++) { var metricValue = rnd.Next(0, 100); customData.Add( new MetricDatum { MetricName = customMetricName, Value = metricValue, TimestampUtc = utcNowMinus15.AddMinutes(i) } ); } await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData); return customData; } /// <summary> /// Wrapper to add metric data to a CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricData">A data object for the metric data.</param> /// <returns>True if successful.</returns> public async Task<bool> PutMetricData(string metricNamespace, List<MetricDatum> metricData) { var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync( new PutMetricDataRequest() { MetricData = metricData, Namespace = metricNamespace, }); return putDataResponse.HttpStatusCode == HttpStatusCode.OK; }
  • Pour API plus de détails, voir PutMetricDatala section AWS SDK for .NET APIRéférence.

C++
SDKpour C++
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Joignez les fichiers requis.

#include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/PutMetricDataRequest.h> #include <iostream>

Placer des données dans la métrique

Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::Dimension dimension; dimension.SetName("UNIQUE_PAGES"); dimension.SetValue("URLS"); Aws::CloudWatch::Model::MetricDatum datum; datum.SetMetricName("PAGES_VISITED"); datum.SetUnit(Aws::CloudWatch::Model::StandardUnit::None); datum.SetValue(data_point); datum.AddDimensions(dimension); Aws::CloudWatch::Model::PutMetricDataRequest request; request.SetNamespace("SITE/TRAFFIC"); request.AddMetricData(datum); auto outcome = cw.PutMetricData(request); if (!outcome.IsSuccess()) { std::cout << "Failed to put sample metric data:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully put sample metric data" << std::endl; }
  • Pour API plus de détails, voir PutMetricDatala section AWS SDK for C++ APIRéférence.

CLI
AWS CLI

Pour publier une métrique personnalisée sur Amazon CloudWatch

L'exemple suivant utilise la put-metric-data commande pour publier une métrique personnalisée sur Amazon CloudWatch :

aws cloudwatch put-metric-data --namespace "Usage Metrics" --metric-data file://metric.json

Les valeurs de la métrique elle-même sont stockées dans le JSON fichiermetric.json.

Voici le contenu de ce fichier :

[ { "MetricName": "New Posts", "Timestamp": "Wednesday, June 12, 2013 8:28:20 PM", "Value": 0.50, "Unit": "Count" } ]

Pour plus d'informations, consultez la section Publication de métriques personnalisées dans le manuel Amazon CloudWatch Developer Guide.

Pour spécifier plusieurs dimensions

L’exemple suivant illustre comment spécifier plusieurs dimensions. Chaque dimension est spécifiée sous la forme d’une paire nom=valeur. Les différentes dimensions sont séparées par une virgule :

aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
  • Pour API plus de détails, voir PutMetricDatala section Référence des AWS CLI commandes.

Java
SDKpour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

public static void addMetricDataForAlarm(CloudWatchClient cw, String fileName) { try { // Read values from the JSON file. JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); // Set an Instant object. String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); Instant instant = Instant.parse(time); MetricDatum datum = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1001.00) .timestamp(instant) .build(); MetricDatum datum2 = MetricDatum.builder() .metricName(customMetricName) .unit(StandardUnit.NONE) .value(1002.00) .timestamp(instant) .build(); List<MetricDatum> metricDataList = new ArrayList<>(); metricDataList.add(datum); metricDataList.add(datum2); PutMetricDataRequest request = PutMetricDataRequest.builder() .namespace(customMetricNamespace) .metricData(metricDataList) .build(); cw.putMetricData(request); System.out.println("Added metric values for for metric " + customMetricName); } catch (CloudWatchException | IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • Pour API plus de détails, voir PutMetricDatala section AWS SDK for Java 2.x APIRéférence.

JavaScript
SDKpour JavaScript (v3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Importez SDK les modules client et appelez leAPI.

import { PutMetricDataCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { // See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html#API_PutMetricData_RequestParameters // and https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html // for more information about the parameters in this command. const command = new PutMetricDataCommand({ MetricData: [ { MetricName: "PAGES_VISITED", Dimensions: [ { Name: "UNIQUE_PAGES", Value: "URLS", }, ], Unit: "None", Value: 1.0, }, ], Namespace: "SITE/TRAFFIC", }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

Créez le client dans un module séparé et exportez-le.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDKpour JavaScript (v2)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create CloudWatch service object var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); // Create parameters JSON for putMetricData var params = { MetricData: [ { MetricName: "PAGES_VISITED", Dimensions: [ { Name: "UNIQUE_PAGES", Value: "URLS", }, ], Unit: "None", Value: 1.0, }, ], Namespace: "SITE/TRAFFIC", }; cw.putMetricData(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", JSON.stringify(data)); } });
Kotlin
SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

suspend fun addMetricDataForAlarm(fileName: String?) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set an Instant object. val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT) val instant = Instant.parse(time) val datum = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1001.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val datum2 = MetricDatum { metricName = customMetricName unit = StandardUnit.None value = 1002.00 timestamp = aws.smithy.kotlin.runtime.time .Instant(instant) } val metricDataList = ArrayList<MetricDatum>() metricDataList.add(datum) metricDataList.add(datum2) val request = PutMetricDataRequest { namespace = customMetricNamespace metricData = metricDataList } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.putMetricData(request) println("Added metric values for for metric $customMetricName") } }
  • Pour API plus de détails, voir PutMetricDatala APIréférence AWS SDK à Kotlin.

PowerShell
Outils pour PowerShell

Exemple 1 : crée un nouvel MetricDatum objet et l'écrit dans Amazon Web Services CloudWatch Metrics.

### Create a MetricDatum .NET object $Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum $Metric.Timestamp = [DateTime]::UtcNow $Metric.MetricName = 'CPU' $Metric.Value = 50 ### Write the metric data to the CloudWatch service Write-CWMetricData -Namespace instance1 -MetricData $Metric
  • Pour API plus de détails, consultez la section PutMetricDataRéférence des AWS Tools for PowerShell applets de commande.

Python
SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def put_metric_data(self, namespace, name, value, unit): """ Sends a single data value to CloudWatch for a metric. This metric is given a timestamp of the current UTC time. :param namespace: The namespace of the metric. :param name: The name of the metric. :param value: The value of the metric. :param unit: The unit of the metric. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[{"MetricName": name, "Value": value, "Unit": unit}], ) logger.info("Put data for metric %s.%s", namespace, name) except ClientError: logger.exception("Couldn't put data for metric %s.%s", namespace, name) raise

Insérez un ensemble de données dans une CloudWatch métrique.

class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def put_metric_data_set(self, namespace, name, timestamp, unit, data_set): """ Sends a set of data to CloudWatch for a metric. All of the data in the set have the same timestamp and unit. :param namespace: The namespace of the metric. :param name: The name of the metric. :param timestamp: The UTC timestamp for the metric. :param unit: The unit of the metric. :param data_set: The set of data to send. This set is a dictionary that contains a list of values and a list of corresponding counts. The value and count lists must be the same length. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[ { "MetricName": name, "Timestamp": timestamp, "Values": data_set["values"], "Counts": data_set["counts"], "Unit": unit, } ], ) logger.info("Put data set for metric %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't put data set for metric %s.%s.", namespace, name) raise
  • Pour API plus de détails, reportez-vous PutMetricDataà la section AWS SDKpour Python (Boto3) Reference. API

Ruby
SDKpour Ruby
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

require "aws-sdk-cloudwatch" # Adds a datapoint to a metric in Amazon CloudWatch. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param metric_namespace [String] The namespace of the metric to add the # datapoint to. # @param metric_name [String] The name of the metric to add the datapoint to. # @param dimension_name [String] The name of the dimension to add the # datapoint to. # @param dimension_value [String] The value of the dimension to add the # datapoint to. # @param metric_value [Float] The value of the datapoint. # @param metric_unit [String] The unit of measurement for the datapoint. # @return [Boolean] # @example # exit 1 unless datapoint_added_to_metric?( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'SITE/TRAFFIC', # 'UniqueVisitors', # 'SiteName', # 'example.com', # 5_885.0, # 'Count' # ) def datapoint_added_to_metric?( cloudwatch_client, metric_namespace, metric_name, dimension_name, dimension_value, metric_value, metric_unit ) cloudwatch_client.put_metric_data( namespace: metric_namespace, metric_data: [ { metric_name: metric_name, dimensions: [ { name: dimension_name, value: dimension_value } ], value: metric_value, unit: metric_unit } ] ) puts "Added data about '#{metric_name}' to namespace " \ "'#{metric_namespace}'." return true rescue StandardError => e puts "Error adding data about '#{metric_name}' to namespace " \ "'#{metric_namespace}': #{e.message}" return false end
  • Pour API plus de détails, voir PutMetricDatala section AWS SDK for Ruby APIRéférence.