Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Gunakan PutMetricData
dengan AWS SDK atau CLI
Contoh kode berikut menunjukkan cara menggunakanPutMetricData
.
Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:
- .NET
-
- AWS SDK for .NET
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; }
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for .NET APIReferensi.
-
- C++
-
- SDKuntuk C ++
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. Sertakan file-file yang diperlukan.
#include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/PutMetricDataRequest.h> #include <iostream>
Masukkan data ke dalam metrik.
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; }
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for C++ APIReferensi.
-
- CLI
-
- AWS CLI
-
Untuk mempublikasikan metrik khusus ke Amazon CloudWatch
Contoh berikut menggunakan
put-metric-data
perintah untuk menerbitkan metrik kustom ke Amazon CloudWatch:aws cloudwatch put-metric-data --namespace
"Usage Metrics"
--metric-datafile://metric.json
Nilai untuk metrik itu sendiri disimpan dalam JSON file,
metric.json
.Berikut adalah isi dari file tersebut:
[ { "MetricName": "New Posts", "Timestamp": "Wednesday, June 12, 2013 8:28:20 PM", "Value": 0.50, "Unit": "Count" } ]
Untuk informasi selengkapnya, lihat Menerbitkan Metrik Kustom di Panduan CloudWatch Pengembang Amazon.
Cara menentukan beberapa dimensi
Contoh berikut menggambarkan cara menentukan beberapa dimensi. Masing-masing dimensi ditentukan sebagai sebuah pasangan Name=Value. Beberapa dimensi dipisahkan menggunakan koma.:
aws cloudwatch put-metric-data --metric-name
Buffers
--namespaceMyNameSpace
--unitBytes
--value231434333
--dimensionsInstanceID=1-23456789,InstanceType=m1.small
-
Untuk API detailnya, lihat PutMetricData
di Referensi AWS CLI Perintah.
-
- Java
-
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. /** * Adds metric data for an alarm asynchronously. * * @param fileName the name of the JSON file containing the metric data * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse */ public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); return rootNode.toString(); // Return JSON as a string for further processing } catch (IOException e) { throw new RuntimeException("Failed to read file", e); } }); return readFileFuture.thenCompose(jsonContent -> { try { com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); Instant instant = Instant.now(); // Create MetricDatum objects. MetricDatum datum1 = 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(datum1); metricDataList.add(datum2); // Build the PutMetricData request. PutMetricDataRequest request = PutMetricDataRequest.builder() .namespace(customMetricNamespace) .metricData(metricDataList) .build(); // Send the request asynchronously. return getAsyncClient().putMetricData(request); } catch (IOException e) { CompletableFuture<PutMetricDataResponse> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new RuntimeException("Failed to parse JSON content", e)); return failedFuture; } }).whenComplete((response, exception) -> { if (exception != null) { logger.error("Failed to put metric data: " + exception.getMessage(), exception); } else { logger.info("Added metric values for metric."); } }); }
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for Java 2.x APIReferensi.
-
- JavaScript
-
- SDKuntuk JavaScript (v3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. Impor modul SDK dan klien dan panggil fileAPI.
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();
Buat klien dalam modul terpisah dan ekspor klien tersebut.
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
-
Untuk informasi selengkapnya, silakan lihat Panduan Developer AWS SDK for JavaScript.
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for JavaScript APIReferensi.
-
- SDKuntuk JavaScript (v2)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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)); } });
-
Untuk informasi selengkapnya, silakan lihat Panduan Developer AWS SDK for JavaScript.
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for JavaScript APIReferensi.
-
- Kotlin
-
- SDKuntuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk API detailnya, lihat PutMetricData AWS
SDKAPIreferensi Kotlin.
-
- PowerShell
-
- Alat untuk PowerShell
-
Contoh 1: Membuat MetricDatum objek baru, dan menuliskannya ke 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
-
Untuk API detailnya, lihat PutMetricDatadi AWS Tools for PowerShell Referensi Cmdlet.
-
- Python
-
- SDKuntuk Python (Boto3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
Masukkan satu set data ke dalam CloudWatch metrik.
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
-
Untuk API detailnya, lihat PutMetricData AWSSDKReferensi Python (Boto3). API
-
- Ruby
-
- SDKuntuk Ruby
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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}'." true rescue StandardError => e puts "Error adding data about '#{metric_name}' to namespace " \ "'#{metric_namespace}': #{e.message}" false end
-
Untuk API detailnya, lihat PutMetricDatadi AWS SDK for Ruby APIReferensi.
-