GetMetricData 搭配 AWS SDK或 使用 CLI - Amazon CloudWatch

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

GetMetricData 搭配 AWS SDK或 使用 CLI

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

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

.NET
AWS SDK for .NET
注意

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

/// <summary> /// Get data for CloudWatch metrics. /// </summary> /// <param name="minutesOfData">The number of minutes of data to include.</param> /// <param name="useDescendingTime">True to return the data descending by time.</param> /// <param name="endDateUtc">The end date for the data, in UTC.</param> /// <param name="maxDataPoints">The maximum data points to include.</param> /// <param name="dataQueries">Optional data queries to include.</param> /// <returns>A list of the requested metric data.</returns> public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null, int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null) { var metricData = new List<MetricDataResult>(); // If no end time is provided, use the current time for the end time. endDateUtc ??= DateTime.UtcNow; var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime()); var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData); // The timezone string should be in the format +0000, so use the timezone offset to format it correctly. var timeZoneString = $"{timeZoneOffset.Hours:D2}{timeZoneOffset.Minutes:D2}"; var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData( new GetMetricDataRequest() { StartTimeUtc = startTimeUtc, EndTimeUtc = endDateUtc.Value, LabelOptions = new LabelOptions { Timezone = timeZoneString }, ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending, MaxDatapoints = maxDataPoints, MetricDataQueries = dataQueries, }); await foreach (var data in paginatedMetricData.MetricDataResults) { metricData.Add(data); } return metricData; }
  • 如需API詳細資訊,請參閱 AWS SDK for .NET API 參考GetMetricData中的 。

CLI
AWS CLI

範例 1:EC2使用數學表達式取得指定 IOPS 的平均總計

下列get-metric-data範例i-abcdef使用結合 CloudWatch EBSReadOps和 指標的指標數學運算式,擷取具有 InstanceID 之EC2執行個體的EBSWriteOps指標值。

aws cloudwatch get-metric-data \ --metric-data-queries file://file.json \ --start-time 2024-09-29T22:10:00Z \ --end-time 2024-09-29T22:15:00Z

file.json 的內容:

[ { "Id": "m3", "Expression": "(m1+m2)/300", "Label": "Avg Total IOPS" }, { "Id": "m1", "MetricStat": { "Metric": { "Namespace": "AWS/EC2", "MetricName": "EBSReadOps", "Dimensions": [ { "Name": "InstanceId", "Value": "i-abcdef" } ] }, "Period": 300, "Stat": "Sum", "Unit": "Count" }, "ReturnData": false }, { "Id": "m2", "MetricStat": { "Metric": { "Namespace": "AWS/EC2", "MetricName": "EBSWriteOps", "Dimensions": [ { "Name": "InstanceId", "Value": "i-abcdef" } ] }, "Period": 300, "Stat": "Sum", "Unit": "Count" }, "ReturnData": false } ]

輸出:

{ "MetricDataResults": [ { "Id": "m3", "Label": "Avg Total IOPS", "Timestamps": [ "2024-09-29T22:10:00+00:00" ], "Values": [ 96.85 ], "StatusCode": "Complete" } ], "Messages": [] }

範例 2:使用 CloudWatch 帳單指標監控預估 AWS 費用

下列get-metric-data範例會從 AWS/Billing 命名空間擷取EstimatedCharges CloudWatch 指標。

aws cloudwatch get-metric-data \ --metric-data-queries '[{"Id":"m1","MetricStat":{"Metric":{"Namespace":"AWS/Billing","MetricName":"EstimatedCharges","Dimensions":[{"Name":"Currency","Value":"USD"}]},"Period":21600,"Stat":"Maximum"}}]' \ --start-time 2024-09-26T12:00:00Z \ --end-time 2024-09-26T18:00:00Z \ --region us-east-1

輸出:

{ "MetricDataResults": [ { "Id": "m1", "Label": "EstimatedCharges", "Timestamps": [ "2024-09-26T12:00:00+00:00" ], "Values": [ 542.38 ], "StatusCode": "Complete" } ], "Messages": [] }

如需詳細資訊,請參閱《Amazon CloudWatch 使用者指南》中的使用數學表達式搭配 CloudWatch 指標

  • 如需API詳細資訊,請參閱 AWS CLI 命令參考GetMetricData中的 。

Java
SDK 適用於 Java 2.x
注意

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

/** * Retrieves custom metric data from the AWS CloudWatch service. * * @param fileName the name of the file containing the custom metric information * @return a {@link CompletableFuture} that completes when the metric data has been retrieved */ public CompletableFuture<Void> getCustomMetricDataAsync(String fileName) { CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> { 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); 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 { // Parse the JSON string to extract relevant values. com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); // Set the current time and date range for metric query. Instant nowDate = Instant.now(); long hours = 1; long minutes = 30; Instant endTime = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES); Metric met = Metric.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); MetricStat metStat = MetricStat.builder() .stat("Maximum") .period(60) // Assuming period in seconds .metric(met) .build(); MetricDataQuery dataQuery = MetricDataQuery.builder() .metricStat(metStat) .id("foo2") .returnData(true) .build(); List<MetricDataQuery> dq = new ArrayList<>(); dq.add(dataQuery); GetMetricDataRequest getMetricDataRequest = GetMetricDataRequest.builder() .maxDatapoints(10) .scanBy(ScanBy.TIMESTAMP_DESCENDING) .startTime(nowDate) .endTime(endTime) .metricDataQueries(dq) .build(); // Call the async method for CloudWatch data retrieval. return getAsyncClient().getMetricData(getMetricDataRequest); } catch (IOException e) { throw new RuntimeException("Failed to parse JSON content", e); } }).thenAccept(response -> { List<MetricDataResult> data = response.metricDataResults(); for (MetricDataResult item : data) { logger.info("The label is: {}", item.label()); logger.info("The status code is: {}", item.statusCode().toString()); } }).exceptionally(exception -> { throw new RuntimeException("Failed to get metric data", exception); }); }
  • 如需API詳細資訊,請參閱 AWS SDK for Java 2.x API 參考GetMetricData中的 。

Kotlin
SDK 適用於 Kotlin
注意

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

suspend fun getCustomMetricData(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 the date. val nowDate = Instant.now() val hours: Long = 1 val minutes: Long = 30 val date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus( minutes, ChronoUnit.MINUTES, ) val met = Metric { metricName = customMetricName namespace = customMetricNamespace } val metStat = MetricStat { stat = "Maximum" period = 1 metric = met } val dataQUery = MetricDataQuery { metricStat = metStat id = "foo2" returnData = true } val dq = ArrayList<MetricDataQuery>() dq.add(dataQUery) val getMetReq = GetMetricDataRequest { maxDatapoints = 10 scanBy = ScanBy.TimestampDescending startTime = aws.smithy.kotlin.runtime.time .Instant(nowDate) endTime = aws.smithy.kotlin.runtime.time .Instant(date2) metricDataQueries = dq } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricData(getMetReq) response.metricDataResults?.forEach { item -> println("The label is ${item.label}") println("The status code is ${item.statusCode}") } } }
  • 如需API詳細資訊,請參閱 GetMetricData 中的 AWS SDK Kotlin API參考

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱搭配 AWS SDK 使用 CloudWatch 。本主題也包含入門的相關資訊,以及先前SDK版本的詳細資訊。