Utilizzare PutMetricData con un AWS SDK o CLI - Esempi di codice dell'AWS SDK

Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples GitHub .

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare PutMetricData con un AWS SDK o CLI

I seguenti esempi di codice mostrano come utilizzarePutMetricData.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:

.NET
AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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; }
C++
SDKper C++
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Includere i file richiesti.

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

Inserimento dei dati in un parametro.

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

Per pubblicare una metrica personalizzata su Amazon CloudWatch

L'esempio seguente utilizza il put-metric-data comando per pubblicare una metrica personalizzata su Amazon CloudWatch:

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

I valori della metrica stessa vengono memorizzati nel JSON file,. metric.json

Ecco i contenuti del file:

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

Per ulteriori informazioni, consulta Publishing Custom Metrics nella Amazon CloudWatch Developer Guide.

Per specificare più dimensioni

Nell'esempio seguente viene illustrato come specificare più dimensioni. Ogni dimensione è specificata come coppia Name=Valore. Più dimensioni sono separate da una virgola:

aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
Java
SDKper Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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); } }
JavaScript
SDKper JavaScript (v3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Importa i moduli SDK e client e chiama ilAPI.

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

Creare il client in un modulo separato ed esportarlo.

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

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
SDKper Kotlin
Nota

c'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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") } }
PowerShell
Strumenti per PowerShell

Esempio 1: crea un nuovo MetricDatum oggetto e lo scrive su 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
  • Per API i dettagli, consulta AWS Tools for PowerShell Cmdlet PutMetricDataReference.

Python
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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

Inserisci un set di dati in una CloudWatch metrica.

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
  • Per API i dettagli, vedere PutMetricDataPython (Boto3) Reference.AWS SDK API

Ruby
SDKper Ruby
Nota

c'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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