Menu
AWS SDK for C++
Developer Guide

Getting Metrics from CloudWatch

Note

These code snippets assume that you understand the material in Getting Started Using the AWS SDK for C++ and have configured default AWS credentials using the information in Providing AWS Credentials.

Listing Metrics

To list CloudWatch metrics, create a ListMetricsRequest and call the CloudWatchClient's ListMetrics function. 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.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/ListMetricsRequest.h> #include <aws/monitoring/model/ListMetricsResult.h> #include <iostream> #include <iomanip>

Code

Copy
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();

The metrics are returned in a ListMetricsResult by calling its GetMetrics function. The results may be paged. To retrieve the next batch of results, call SetNextToken on the original request object with the return value of the ListMetricsResult object's GetNextToken function, and pass the modified request object back to another call to ListMetrics.

See the complete example.

More Information