getMetricData from AWS Cloud Watch using Java SDK: In this tutorial, we will see how to get the Cloud watch metric data from AWS using Java SDK.

AWS has multiple services, Cloud watch is one of the services which is used to get details monitoring of services you have enabled.

By Default, AWS will give you limited access to monitoring without any extra payment but we need to get in detailed monitoring of any instance or any service in ec2 or dynamnodb we need to enable cloudwatch.

There are multiple SDKs available with AWS to get metric information or modify information.

We are using JAVA SDK to get the metrics information. In a single method call, we can get up to 100 metrics and we can use the custom Metric aswell.

First Create a Java maven project and add below dependency management into your pom file

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-bom</artifactId>
        <version>1.11.682</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
 

Add below dependencies to your POM file 

  <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-cloudwatch</artifactId>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-cloudwatchmetrics</artifactId>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-events</artifactId>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-logs</artifactId>
    </dependency>

Then Create you Request body which need to be send to AWS Console 

{
  "startTime": 1575020059313,
  "endTime": 1575020659313,
  "metricDataQueries": [
    {
      "id": "m1",
      "metricStat": {
        "metric": {
          "namespace": "AWS/EC2",
          "metricName": "CPUUtilization",
          "dimensions": [
            {
              "name": "InstanceId",
              "value": "value of your instance"
            }
          ]
        },
        "period": 120,
        "stat": "Maximum"
      }
    }
  ]
}
  • We need to pass the start and end time to get the time range
  • We can send multiple json object in metricDataQueries to get multiple metrics 
  • For Getting  dimensions object use below Code 

 

import java.io.IOException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
import com.amazonaws.services.cloudwatch.model.ListMetricsRequest;
import com.amazonaws.services.cloudwatch.model.ListMetricsResult;
import com.amazonaws.services.cloudwatch.model.Metric;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * Lists CloudWatch metrics
 */
public class ListMetrics {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("Access Key", "Secret Key");
        AmazonCloudWatch cloudWatch = AmazonCloudWatchClientBuilder.standard().withCredentials(
        	new AWSStaticCredentialsProvider(awsCreds))
		    .withRegion(Regions.AP_SOUTH_1).build();
        
        String name = "NetworkOut";
        String namespace =  "AWS/EC2";

        ListMetricsRequest request = new ListMetricsRequest()
                .withMetricName(name)
                .withNamespace(namespace);

        boolean done = false;
        
        while(!done) {
            ListMetricsResult response = cloudWatch.listMetrics(request);

            for(Metric metric : response.getMetrics()) {
                System.out.printf(
                    "Retrieved metric %s", metric.getDimensions());
            }

            request.setNextToken(response.getNextToken());

            if(response.getNextToken() == null) {
                done = true;
            }
        }
    }
}
  • After getting dimensions and required metrics create Json Object 
  • Now create an actual call for getting metrics 
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.GetMetricDataRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricDataResult;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Getmetrices {

	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
		// TODO Auto-generated method stub
		BasicAWSCredentials awsCreds = new BasicAWSCredentials("Access key", "Secret Key");
		AWSStaticCredentialsProvider cred = new AWSStaticCredentialsProvider(awsCreds);
		AmazonCloudWatchClient client = new AmazonCloudWatchClient(cred.getCredentials());
		client.withRegion(Regions.AP_SOUTH_1);
		long ONE_MINUTE_IN_MILLIS = 60000;// millisecs
		Calendar date = Calendar.getInstance();
		long t = date.getTimeInMillis();
		Date afterAddingTenMins = new Date(t - (10 * ONE_MINUTE_IN_MILLIS));
		String data = "{\"startTime\":"
		    + afterAddingTenMins.getTime()
		    + ",\"endTime\":"
		    + new Date().getTime()
		    + ",\"metricDataQueries\":[{\"id\":\"m1\",\"metricStat\":"
		    + "{\"metric\":{\"namespace\":\"AWS/EC2\",\"metricName\":\"CPUUtilization\",\"dimensions\":"
		    + "[{\"name\": \"InstanceId\",\"value\": \"value of instance\"}]},\"period\":120,\"stat\":\"Maximum\"}}]}";
		System.out.println(data);
		ObjectMapper objectMapper = new ObjectMapper();
		GetMetricDataRequest requestObj = objectMapper.readValue(data, GetMetricDataRequest.class);
		GetMetricDataResult result = client.getMetricData(requestObj);
		String jsonStr = objectMapper.writeValueAsString(result);
		System.out.println("Output :" + jsonStr);
	}

}

Run GetmetricData class as for output.

Thanks

Also Read: HTML Code for Popup Window 

 

getMetricData from AWS Cloud Watch using Java SDK Example

Leave a Reply

Your email address will not be published. Required fields are marked *