Use ListMetrics com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use ListMetrics com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o ListMetrics.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto nos seguintes exemplos de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; }
  • Para API obter detalhes, consulte ListMetricsem AWS SDK for .NET APIReferência.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Inclua os arquivos necessários.

#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>

Liste as métricas.

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(); }
  • Para API obter detalhes, consulte ListMetricsem AWS SDK for C++ APIReferência.

CLI
AWS CLI

Para listar as métricas da Amazon SNS

O list-metrics exemplo a seguir exibe as métricas da AmazonSNS.

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

Saída:

{ "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" } ] }
  • Para API obter detalhes, consulte ListMetricsna Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } } }
  • Para API obter detalhes, consulte ListMetricsem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Importe os módulos SDK e do cliente e chame API o.

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); };

Crie o cliente em um módulo separado e exporte-o.

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDKpara JavaScript (v2)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }
  • Para API obter detalhes, consulte a ListMetricsreferência AWS SDKdo Kotlin API.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
  • Para API obter detalhes, consulte a ListMetricsReferência AWS SDK do Python (Boto3). API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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__
  • Para API obter detalhes, consulte ListMetricsem AWS SDK for Ruby APIReferência.

SAP ABAP
SDKpara SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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.
  • Para API obter detalhes, consulte ListMetrics AWSSDKpara SAP ABAP API referência.