GetMetricStatisticsOR와 함께 사용 AWS SDK CLI - AWS SDK코드 예제

AWS 문서 AWS SDK SDK 예제 GitHub 리포지토리에 더 많은 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

GetMetricStatisticsOR와 함께 사용 AWS SDK CLI

다음 코드 예제는 GetMetricStatistics의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Get billing statistics using a call to a wrapper class. /// </summary> /// <returns>A collection of billing statistics.</returns> private static async Task<List<Datapoint>> SetupBillingStatistics() { // Make a request for EstimatedCharges with a period of one day for the past seven days. var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics( "AWS/Billing", "EstimatedCharges", new List<string>() { "Maximum" }, new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } }, 7, 86400); billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList(); return billingStatistics; } /// <summary> /// Wrapper to get statistics for a specific CloudWatch metric. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metricName">The name of the metric.</param> /// <param name="statistics">The list of statistics to include.</param> /// <param name="dimensions">The list of dimensions to include.</param> /// <param name="days">The number of days in the past to include.</param> /// <param name="period">The period for the data.</param> /// <returns>A list of DataPoint objects for the statistics.</returns> public async Task<List<Datapoint>> GetMetricStatistics(string metricNamespace, string metricName, List<string> statistics, List<Dimension> dimensions, int days, int period) { var metricStatistics = await _amazonCloudWatch.GetMetricStatisticsAsync( new GetMetricStatisticsRequest() { Namespace = metricNamespace, MetricName = metricName, Dimensions = dimensions, Statistics = statistics, StartTimeUtc = DateTime.UtcNow.AddDays(-days), EndTimeUtc = DateTime.UtcNow, Period = period }); return metricStatistics.Datapoints; }
CLI
AWS CLI

EC2인스턴스당 CPU 사용률을 구하려면

다음 예제에서는 get-metric-statistics 명령을 사용하여 ID가 CPU i-abcdef인 EC2 인스턴스의 사용률을 가져옵니다.

aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start-time 2014-04-08T23:18:00Z --end-time 2014-04-09T23:18:00Z --period 3600 --namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=i-abcdef

출력:

{ "Datapoints": [ { "Timestamp": "2014-04-09T11:18:00Z", "Maximum": 44.79, "Unit": "Percent" }, { "Timestamp": "2014-04-09T20:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T19:18:00Z", "Maximum": 50.85, "Unit": "Percent" }, { "Timestamp": "2014-04-09T09:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T03:18:00Z", "Maximum": 76.84, "Unit": "Percent" }, { "Timestamp": "2014-04-09T21:18:00Z", "Maximum": 48.96, "Unit": "Percent" }, { "Timestamp": "2014-04-09T14:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T08:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T16:18:00Z", "Maximum": 45.55, "Unit": "Percent" }, { "Timestamp": "2014-04-09T06:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T13:18:00Z", "Maximum": 45.08, "Unit": "Percent" }, { "Timestamp": "2014-04-09T05:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T18:18:00Z", "Maximum": 46.88, "Unit": "Percent" }, { "Timestamp": "2014-04-09T17:18:00Z", "Maximum": 52.08, "Unit": "Percent" }, { "Timestamp": "2014-04-09T07:18:00Z", "Maximum": 47.92, "Unit": "Percent" }, { "Timestamp": "2014-04-09T02:18:00Z", "Maximum": 51.23, "Unit": "Percent" }, { "Timestamp": "2014-04-09T12:18:00Z", "Maximum": 47.67, "Unit": "Percent" }, { "Timestamp": "2014-04-08T23:18:00Z", "Maximum": 46.88, "Unit": "Percent" }, { "Timestamp": "2014-04-09T10:18:00Z", "Maximum": 51.91, "Unit": "Percent" }, { "Timestamp": "2014-04-09T04:18:00Z", "Maximum": 47.13, "Unit": "Percent" }, { "Timestamp": "2014-04-09T15:18:00Z", "Maximum": 48.96, "Unit": "Percent" }, { "Timestamp": "2014-04-09T00:18:00Z", "Maximum": 48.16, "Unit": "Percent" }, { "Timestamp": "2014-04-09T01:18:00Z", "Maximum": 49.18, "Unit": "Percent" } ], "Label": "CPUUtilization" }

여러 측정기준을 지정하는 방법

다음 예제는 여러 측정기준을 지정하는 방법을 보여줍니다. 각 측정기준은 이름과 값 사이에 쉼표가 있는 이름/값 페어로 지정됩니다. 여러 측정기준은 공백으로 구분됩니다. 단일 지표에 여러 개의 측정기준이 포함된 경우에는 정의된 모든 측정기준에 대해 값을 지정해야 합니다.

get-metric-statistics명령을 사용하는 더 많은 예를 보려면 Amazon CloudWatch 개발자 안내서의 지표에 대한 통계 가져오기를 참조하십시오.

aws cloudwatch get-metric-statistics --metric-name Buffers --namespace MyNameSpace --dimensions Name=InstanceID,Value=i-abcdef Name=InstanceType,Value=m1.small --start-time 2016-10-15T04:00:00Z --end-time 2016-10-19T07:00:00Z --statistics Average --period 60
Java
SDK자바 2.x의 경우
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public static void getAndDisplayMetricStatistics(CloudWatchClient cw, String nameSpace, String metVal, String metricOption, String date, Dimension myDimension) { try { Instant start = Instant.parse(date); Instant endDate = Instant.now(); GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() .endTime(endDate) .startTime(start) .dimensions(myDimension) .metricName(metVal) .namespace(nameSpace) .period(86400) .statistics(Statistic.fromValue(metricOption)) .build(); GetMetricStatisticsResponse response = cw.getMetricStatistics(statisticsRequest); List<Datapoint> data = response.datapoints(); if (!data.isEmpty()) { for (Datapoint datapoint : data) { System.out .println("Timestamp: " + datapoint.timestamp() + " Maximum value: " + datapoint.maximum()); } } else { System.out.println("The returned data list is empty"); } } catch (CloudWatchException e) { System.err.println(e.getMessage()); System.exit(1); } }
Kotlin
SDK코틀린의 경우
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun getAndDisplayMetricStatistics( nameSpaceVal: String, metVal: String, metricOption: String, date: String, myDimension: Dimension, ) { val start = Instant.parse(date) val endDate = Instant.now() val statisticsRequest = GetMetricStatisticsRequest { endTime = aws.smithy.kotlin.runtime.time .Instant(endDate) startTime = aws.smithy.kotlin.runtime.time .Instant(start) dimensions = listOf(myDimension) metricName = metVal namespace = nameSpaceVal period = 86400 statistics = listOf(Statistic.fromValue(metricOption)) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricStatistics(statisticsRequest) val data = response.datapoints if (data != null) { if (data.isNotEmpty()) { for (datapoint in data) { println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}") } } else { println("The returned data list is empty") } } } }
Python
SDK파이썬용 (보토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 get_metric_statistics(self, namespace, name, start, end, period, stat_types): """ Gets statistics for a metric within a specified time span. Metrics are grouped into the specified period. :param namespace: The namespace of the metric. :param name: The name of the metric. :param start: The UTC start time of the time span to retrieve. :param end: The UTC end time of the time span to retrieve. :param period: The period, in seconds, in which to group metrics. The period must match the granularity of the metric, which depends on the metric's age. For example, metrics that are older than three hours have a one-minute granularity, so the period must be at least 60 and must be a multiple of 60. :param stat_types: The type of statistics to retrieve, such as average value or maximum value. :return: The retrieved statistics for the metric. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) stats = metric.get_statistics( StartTime=start, EndTime=end, Period=period, Statistics=stat_types ) logger.info( "Got %s statistics for %s.", len(stats["Datapoints"]), stats["Label"] ) except ClientError: logger.exception("Couldn't get statistics for %s.%s.", namespace, name) raise else: return stats
  • 자세한 API AWS SDK내용은 Python (Boto3) API 참조를 참조하십시오 GetMetricStatistics.