Get metrics from CloudWatch - Amazon SDK for Java 2.x
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Get metrics from CloudWatch

Listing metrics

To list CloudWatch metrics, create a ListMetricsRequest and call the CloudWatchClient’s listMetrics method. You can use the ListMetricsRequest to filter the returned metrics by namespace, metric name, or dimensions.

Note

A list of metrics and dimensions that are posted by Amazon services can be found within the Amazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User Guide.

Imports

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;

Code

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

The metrics are returned in a ListMetricsResponse by calling its getMetrics method.

The results may be paged. To retrieve the next batch of results, call nextToken on the response object and use the token value to build a new request object. Then call the listMetrics method again with the new request.

See the complete example on GitHub.

More information