搭PutMetricData配 AWS SDK或使用 CLI - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutMetricData配 AWS SDK或使用 CLI

下列程式碼範例會示範如何使用PutMetricData

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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; }
  • 如需詳API細資訊,請參閱AWS SDK for .NET API參考PutMetricData中的。

C++
SDK對於 C ++
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

包括必需的檔案。

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

將資料放入指標。

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; }
  • 如需詳API細資訊,請參閱AWS SDK for C++ API參考PutMetricData中的。

CLI
AWS CLI

若要將自訂指標發佈到 Amazon CloudWatch

下列範例使用put-metric-data命令將自訂指標發佈到 Amazon CloudWatch:

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

量度本身的值儲存在JSON檔案中metric.json

以下是該檔案的內容:

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

如需詳細資訊,請參閱 Amazon CloudWatch 開發人員指南中的發佈自訂指標。

指定多個維度

下列範例說明如何指定多個維度。每個維度均指定為 Name=Value 對。使用逗號分隔多個維度:

aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
  • 如需詳API細資訊,請參閱AWS CLI 指令參考PutMetricData中的。

Java
SDK對於爪哇 2.x
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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); } }
  • 如需詳API細資訊,請參閱AWS SDK for Java 2.x API參考PutMetricData中的。

JavaScript
SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

匯入SDK和用戶端模組並呼叫API.

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

在單獨的模組中建立用戶端並將其匯出。

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK對於 JavaScript (第 2 個)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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
SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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") } }
  • 有API關詳細資訊,請參閱PutMetricDataAWS SDK的以取得 Kotlin API 的參考資料

PowerShell
適用的工具 PowerShell

範例 1:建立新 MetricDatum 物件,並將其寫入 Amazon Web Services CloudWatch 指標。

### 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
  • 如需詳API細資訊,請參閱AWS Tools for PowerShell 指令程PutMetricData式參考中的。

Python
SDK對於 Python(肉毒桿菌 3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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

將一組資料放入指 CloudWatch 標中。

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
  • 如需詳API細資訊,請參閱PutMetricDataAWS SDK的《Python (博多 3) API 參考》。

Ruby
SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 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
  • 如需詳API細資訊,請參閱AWS SDK for Ruby API參考PutMetricData中的。