AWS SDK for Java version 2
Developer Guide

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above.

Getting 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 AWS services can be found within the Amazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User Guide.

Imports

import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse; import software.amazon.awssdk.services.cloudwatch.model.Metric; /** * Lists CloudWatch metrics */

Code

CloudWatchClient cw = CloudWatchClient.builder().build(); boolean done = false; String next_token = null; while(!done) { ListMetricsResponse response; if (next_token == null) { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); response = cw.listMetrics(request); } else { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .nextToken(next_token) .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 { next_token = response.nextToken(); } }

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