Search code examples
c#amazon-web-servicescloudamazon-cloudwatchcloudwatch

How to use the nextToken in the ListMetrics function


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.


Solution

  • 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
    }