How to emit Cloud-watch metrics

Sun, Mar 26, 2023

Read in 1 minutes

Overview

We can create cloud-watch metrics in two ways.

Creating metrics from log events using filters

  1. Add logs for particular scenario in our service (For example add log 503 error service unavailable when calling external service)
  2. Then add filter based on the log statement.
  3. [.., metrics = “METRICS”, metricName = “EXTERNAL CALL FAIL” metricValue] https://docs.amazonaws.cn/en_us/AmazonCloudWatch/latest/logs/MonitoringLogData.html

Create Cloud-watch metrics in java SDK

Libraries Used:

AWSCloudWatchJavaClient

Specify the dimension. Here the dimension is marketplace, productType.PutMetricDataRequest will actually emit the metrics.

public void emitProductMetrics (final String name , String marketplace , String productType){

final Dimension marketplaceDimension = new Dimension()
.withName(ProductMetrics.Dimensions.MARKETPLACE)
.withValue(marketplace));

final Dimension productTypeDimension = new Dimension()
.withName(ProductMetrics.Dimensions.PRODUCT_TYPE)
.withValue(productType);

final MetricDatum ProductMetricDatum = new MetricDatum()
.withMetricName(name)
.withUnit(StandardUnit.None)
.withValue(1.0)
.withDimensions(marketplaceDimension,productTypeDimension);

final List<MetricDatum> MetricDataToEmit = new ArrayList<>();

MetricDataToEmit.add(ProductMetricDatum);

final PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest()
.withNamespace(ProductMetrics,PRODUCTS_METRICS_NAMESPACE)
.withMetricData(MetricDataToEmit);

amazonCloudWatch.putMetricData(putMetricDataRequest);

}