Use PutMetricData com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use PutMetricData com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o PutMetricData.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto nos seguintes exemplos de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; }
  • Para API obter detalhes, consulte PutMetricDataem AWS SDK for .NET APIReferência.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Inclua os arquivos necessários.

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

Insira dados na métrica.

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; }
  • Para API obter detalhes, consulte PutMetricDataem AWS SDK for C++ APIReferência.

CLI
AWS CLI

Para publicar uma métrica personalizada na Amazon CloudWatch

O exemplo a seguir usa o put-metric-data comando para publicar uma métrica personalizada na Amazon CloudWatch:

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

Os valores da métrica em si são armazenados no JSON arquivo,metric.json.

Veja o conteúdo desse arquivo:

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

Para obter mais informações, consulte Publicação de métricas personalizadas no Amazon CloudWatch Developer Guide.

Como especificar diversas dimensões

O exemplo a seguir ilustra como especificar diversas dimensões. Cada dimensão é especificada como um par de nome/valor. As diversas dimensões são separadas por uma vírgula.

aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
  • Para API obter detalhes, consulte PutMetricDatana Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } }
  • Para API obter detalhes, consulte PutMetricDataem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Importe os módulos SDK e do cliente e chame API o.

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

Crie o cliente em um módulo separado e exporte-o.

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

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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") } }
  • Para API obter detalhes, consulte a PutMetricDatareferência AWS SDKdo Kotlin API.

PowerShell
Ferramentas para PowerShell

Exemplo 1: cria um novo MetricDatum objeto e o grava no 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
  • Para API obter detalhes, consulte PutMetricDataem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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

Coloque um conjunto de dados em uma CloudWatch métrica.

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
  • Para API obter detalhes, consulte a PutMetricDataReferência AWS SDK do Python (Boto3). API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
  • Para API obter detalhes, consulte PutMetricDataem AWS SDK for Ruby APIReferência.