使用 Amazon 开发工具包列出 CloudWatch 指标 - Amazon CloudWatch
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包列出 CloudWatch 指标

以下代码示例展示如何列出 Amazon CloudWatch 指标。

.NET
Amazon SDK for .NET

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; /// <summary> /// This example demonstrates how to list metrics for Amazon CloudWatch. /// The example was created using the AWS SDK for .NET version 3.7 and /// .NET Core 5.0. /// </summary> public class ListMetrics { public static async Task Main() { IAmazonCloudWatch cwClient = new AmazonCloudWatchClient(); var filter = new DimensionFilter { Name = "InstanceType", Value = "t1.micro", }; string metricName = "CPUUtilization"; string namespaceName = "AWS/EC2"; await ListMetricsAsync(cwClient, filter, metricName, namespaceName); } /// <summary> /// Retrieve CloudWatch metrics using the supplied filter, metrics name, /// and namespace. /// </summary> /// <param name="client">An initialized CloudWatch client.</param> /// <param name="filter">The filter to apply in retrieving metrics.</param> /// <param name="metricName">The metric name for which to retrieve /// information.</param> /// <param name="nameSpaceName">The name of the namespace from which /// to retrieve metric information.</param> public static async Task ListMetricsAsync( IAmazonCloudWatch client, DimensionFilter filter, string metricName, string nameSpaceName) { var request = new ListMetricsRequest { Dimensions = new List<DimensionFilter>() { filter }, MetricName = metricName, Namespace = nameSpaceName, }; var response = new ListMetricsResponse(); do { response = await client.ListMetricsAsync(request); if (response.Metrics.Count > 0) { foreach (var metric in response.Metrics) { Console.WriteLine(metric.MetricName + " (" + metric.Namespace + ")"); foreach (var dimension in metric.Dimensions) { Console.WriteLine(" " + dimension.Name + ": " + dimension.Value); } } } else { Console.WriteLine("No metrics found."); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 ListMetrics

Java
SDK for Java 2.x

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); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 ListMetrics

JavaScript
SDK for JavaScript V3

在单独的模块中创建客户端并将其导出。

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

导入开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import { ListMetricsCommand } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { Dimensions: [ { Name: "LogGroupName" /* required */, }, ], MetricName: "IncomingLogEvents", Namespace: "AWS/Logs", }; export const run = async () => { try { const data = await cwClient.send(new ListMetricsCommand(params)); console.log("Success. Metrics:", JSON.stringify(data.Metrics)); return data; } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2

// 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)); } });
Python
适用于 Python (Boto3) 的 SDK

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
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon 适用于 Python (Boto3) 的 SDK API 参考中的 ListMetrics

有关 Amazon 开发工具包开发人员指南和代码示例的完整列表,包括帮助入门和有关早期版本的信息,请参阅 将 CloudWatch 与 Amazon 开发工具包结合使用