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

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

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

ListMetricsOR와 함께 사용 AWS SDK CLI

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

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

.NET
AWS SDK for .NET
참고

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

/// <summary> /// List metrics available, optionally within a namespace. /// </summary> /// <param name="metricNamespace">Optional CloudWatch namespace to use when listing metrics.</param> /// <param name="filter">Optional dimension filter.</param> /// <param name="metricName">Optional metric name filter.</param> /// <returns>The list of metrics.</returns> public async Task<List<Metric>> ListMetrics(string? metricNamespace = null, DimensionFilter? filter = null, string? metricName = null) { var results = new List<Metric>(); var paginateMetrics = _amazonCloudWatch.Paginators.ListMetrics( new ListMetricsRequest { Namespace = metricNamespace, Dimensions = filter != null ? new List<DimensionFilter> { filter } : null, MetricName = metricName }); // Get the entire list using the paginator. await foreach (var metric in paginateMetrics.Metrics) { results.Add(metric); } return results; }
C++
SDKC++의 경우
참고

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

필수 파일을 포함합니다.

#include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/ListMetricsRequest.h> #include <aws/monitoring/model/ListMetricsResult.h> #include <iomanip> #include <iostream>

지표를 나열합니다.

Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::ListMetricsRequest request; if (argc > 1) { request.SetMetricName(argv[1]); } if (argc > 2) { request.SetNamespace(argv[2]); } bool done = false; bool header = false; while (!done) { auto outcome = cw.ListMetrics(request); if (!outcome.IsSuccess()) { std::cout << "Failed to list CloudWatch metrics:" << outcome.GetError().GetMessage() << std::endl; break; } if (!header) { std::cout << std::left << std::setw(48) << "MetricName" << std::setw(32) << "Namespace" << "DimensionNameValuePairs" << std::endl; header = true; } const auto &metrics = outcome.GetResult().GetMetrics(); for (const auto &metric : metrics) { std::cout << std::left << std::setw(48) << metric.GetMetricName() << std::setw(32) << metric.GetNamespace(); const auto &dimensions = metric.GetDimensions(); for (auto iter = dimensions.cbegin(); iter != dimensions.cend(); ++iter) { const auto &dimkv = *iter; std::cout << dimkv.GetName() << " = " << dimkv.GetValue(); if (iter + 1 != dimensions.cend()) { std::cout << ", "; } } std::cout << std::endl; } const auto &next_token = outcome.GetResult().GetNextToken(); request.SetNextToken(next_token); done = next_token.empty(); }
CLI
AWS CLI

Amazon의 측정치를 나열하려면 SNS

다음 list-metrics 예는 Amazon의 메트릭을 보여줍니다SNS.

aws cloudwatch list-metrics \ --namespace "AWS/SNS"

출력:

{ "Metrics": [ { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "PublishSize" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "PublishSize" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "NumberOfNotificationsFailed" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "NumberOfNotificationsDelivered" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "NotifyMe" } ], "MetricName": "NumberOfMessagesPublished" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfMessagesPublished" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfNotificationsDelivered" }, { "Namespace": "AWS/SNS", "Dimensions": [ { "Name": "TopicName", "Value": "CFO" } ], "MetricName": "NumberOfNotificationsFailed" } ] }
  • 자세한 API 내용은 AWS CLI 명령 ListMetrics참조를 참조하십시오.

Java
SDK자바 2.x의 경우
참고

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

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse; import software.amazon.awssdk.services.cloudwatch.model.Metric; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListMetrics { public static void main(String[] args) { final String usage = """ Usage: <namespace>\s Where: namespace - The namespace to filter against (for example, AWS/EC2).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); listMets(cw, namespace); cw.close(); } public static void listMets(CloudWatchClient cw, String namespace) { boolean done = false; String nextToken = null; try { while (!done) { ListMetricsResponse response; if (nextToken == null) { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); response = cw.listMetrics(request); } else { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .nextToken(nextToken) .build(); response = cw.listMetrics(request); } for (Metric metric : response.metrics()) { System.out.printf("Retrieved metric %s", metric.metricName()); System.out.println(); } if (response.nextToken() == null) { done = true; } else { nextToken = response.nextToken(); } } } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
JavaScript
SDK JavaScript (v3) 에 대한
참고

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

SDK및 클라이언트 모듈을 가져와서 호출하십시오API.

import { ListMetricsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; export const main = () => { // Use the AWS console to see available namespaces and metric names. Custom metrics can also be created. // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/viewing_metrics_with_cloudwatch.html const command = new ListMetricsCommand({ Dimensions: [ { Name: "LogGroupName", }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }); return client.send(command); };

별도의 모듈에서 클라이언트를 생성하고 내보냅니다.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK JavaScript (v2) 에 대한
참고

더 많은 정보가 있습니다 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" }); var params = { Dimensions: [ { Name: "LogGroupName" /* required */, }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }; cw.listMetrics(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Metrics", JSON.stringify(data.Metrics)); } });
Kotlin
SDK코틀린의 경우
참고

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

suspend fun listMets(namespaceVal: String?): ArrayList<String>? { val metList = ArrayList<String>() val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val reponse = cwClient.listMetrics(request) reponse.metrics?.forEach { metrics -> val data = metrics.metricName if (!metList.contains(data)) { metList.add(data!!) } } } return metList }
  • 자세한 API AWS SDK내용은 Kotlin API 참조를 참조하세요 ListMetrics.

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 list_metrics(self, namespace, name, recent=False): """ Gets the metrics within a namespace that have the specified name. If the metric has no dimensions, a single metric is returned. Otherwise, metrics for all dimensions are returned. :param namespace: The namespace of the metric. :param name: The name of the metric. :param recent: When True, only metrics that have been active in the last three hours are returned. :return: An iterator that yields the retrieved metrics. """ try: kwargs = {"Namespace": namespace, "MetricName": name} if recent: kwargs["RecentlyActive"] = "PT3H" # List past 3 hours only metric_iter = self.cloudwatch_resource.metrics.filter(**kwargs) logger.info("Got metrics for %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't get metrics for %s.%s.", namespace, name) raise else: return metric_iter
  • 자세한 API AWS SDK내용은 Python (Boto3) API 참조를 참조하십시오 ListMetrics.

Ruby
SDK루비의 경우
참고

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

# Lists available metrics for a metric namespace in Amazon CloudWatch. # # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. # @param metric_namespace [String] The namespace of the metric. # @example # list_metrics_for_namespace( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'SITE/TRAFFIC' # ) def list_metrics_for_namespace(cloudwatch_client, metric_namespace) response = cloudwatch_client.list_metrics(namespace: metric_namespace) if response.metrics.count.positive? response.metrics.each do |metric| puts " Metric name: #{metric.metric_name}" if metric.dimensions.count.positive? puts " Dimensions:" metric.dimensions.each do |dimension| puts " Name: #{dimension.name}, Value: #{dimension.value}" end else puts "No dimensions found." end end else puts "No metrics found for namespace '#{metric_namespace}'. " \ "Note that it could take up to 15 minutes for recently-added metrics " \ "to become available." end end # Example usage: def run_me metric_namespace = "SITE/TRAFFIC" # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. region = "us-east-1" cloudwatch_client = Aws::CloudWatch::Client.new(region: region) # Add three datapoints. puts "Continuing..." unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, "UniqueVisitors", "SiteName", "example.com", 5_885.0, "Count" ) puts "Continuing..." unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, "UniqueVisits", "SiteName", "example.com", 8_628.0, "Count" ) puts "Continuing..." unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, "PageViews", "PageURL", "example.html", 18_057.0, "Count" ) puts "Metrics for namespace '#{metric_namespace}':" list_metrics_for_namespace(cloudwatch_client, metric_namespace) end run_me if $PROGRAM_NAME == __FILE__
SAP ABAP
SDK에 대한 SAP ABAP
참고

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

"The following list-metrics example displays the metrics for Amazon CloudWatch." TRY. oo_result = lo_cwt->listmetrics( " oo_result is returned for testing purposes. " iv_namespace = iv_namespace ). DATA(lt_metrics) = oo_result->get_metrics( ). MESSAGE 'Metrics retrieved.' TYPE 'I'. CATCH /aws1/cx_cwtinvparamvalueex . MESSAGE 'The specified argument was not valid.' TYPE 'E'. ENDTRY.
  • 자세한 API AWS SDK내용은 ListMetrics에서 SAP ABAP API 참조를 참조하십시오.