Gunakan ListMetrics dengan AWS SDK atau CLI - AWS SDKContoh Kode

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 ListMetrics dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanListMetrics.

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> /// 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; }
  • Untuk API detailnya, lihat ListMetricsdi 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/ListMetricsRequest.h> #include <aws/monitoring/model/ListMetricsResult.h> #include <iomanip> #include <iostream>

Membuat daftar metrik.

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(); }
  • Untuk API detailnya, lihat ListMetricsdi AWS SDK for C++ APIReferensi.

CLI
AWS CLI

Untuk membuat daftar metrik untuk Amazon SNS

list-metricsContoh berikut menampilkan metrik untuk AmazonSNS.

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

Output:

{ "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" } ] }
  • Untuk API detailnya, lihat ListMetricsdi 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.

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); } } }
  • Untuk API detailnya, lihat ListMetricsdi 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 { 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); };

Buat klien dalam modul terpisah dan ekspor klien tersebut.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
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" }); 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
SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 }
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 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
  • Untuk API detailnya, lihat ListMetrics 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.

# 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__
  • Untuk API detailnya, lihat ListMetricsdi AWS SDK for Ruby APIReferensi.

SAP ABAP
SDKuntuk SAP ABAP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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.
  • Untuk API detailnya, lihat ListMetrics AWSSDKuntuk SAP ABAP API referensi.