How to use the nextToken in the ListMetrics function

1.9k views Asked by At

I am trying to list all the metrics stored in CloudWatch using the function: ListMetrics. The function returns about 500 metrics and a string value called NextToken that is to be used in the next call to get the rest of the metrics.

This is my code below but I do not know how to use the NextToken to get the rest of the metrics.

  // creates the CloudWatch client
            var cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
        // initialses the list metrics request
        ListMetricsRequest lmr = new ListMetricsRequest();
        ListMetricsResponse lmresponse = cw.ListMetrics(lmr);



        // loop that uses the token to get all the metrics available
        // not finished yet
        do
        {
            lmresponse = cw.ListMetrics(lmr);
            lmresponse.NextToken;

        } while (lmresponse.NextToken != null);

I would like to know how to use the NextToken in order to get the rest of the metrics. I couldn't find any examples online unfortunately.

3

There are 3 answers

1
tpolyak On BEST ANSWER

If there's a NextToken in the response, you can use it in the next request:

// creates the CloudWatch client
var cw =  Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
// initialses the list metrics request
ListMetricsRequest lmr = new ListMetricsRequest();
ListMetricsResponse lmresponse = cw.ListMetrics(lmr);

while (lmresponse.NextToken != null);
{
    // set request token 
    lmr.NextToken = lmresponse.NextToken;
    lmresponse = cw.ListMetrics(lmr);

    // Process metrics found in lmresponse.Metrics
} 
1
EFeit On

If you just need to loop over the entire list of metrics, I would use a foreach loop. The code would look like this:

        // creates the CloudWatch client
        var cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
        // initialses the list metrics request
        ListMetricsRequest lmr = new ListMetricsRequest();
        ListMetricsResponse lmresponse = cw.ListMetrics(lmr);

        foreach (Metric metric in lmresponse.Metrics)
        {
            // do something with
            // metric.MetricName;
            // metric.Dimensions;
            // etc
        }
0
BigMan On

Putting it in a do-while loop ensures that the ListMetrics function keeps getting called and lists all the metrics as long as the nextToken is not null.

private string nextToken;

do
{
  lmrequest.NextToken = nextToken;
  lmresponse = cloudwatch.ListMetrics(lmrequest);
  nextToken = lmresponse.NextToken;
} while (nextToken != null);