In any environment it is essential to collect and have a well organized and easy way of having live stats and information in order to have control over the state and status of the running applications, specially in production. In order to do so, at Ensolvers we use a battery of resources, from traditional logging to dashboards, charts and many more.
In this tech note, we will explore how we can use Micrometer in the context of a Spring Boot application to publish metrics to AWS CloudWatch.
What is Micrometer?
Micrometer is a Java library that provides a simple way to collect metrics from your application and send them to various monitoring and alerting tools such as New Relic, Prometheus, Atlas, CloudWatch and others. On this note, we will focus on integrating with CloudWatch.
Micrometer key concepts
Setting up Micrometer on Spring Boot
First, we need to add the Maven dependency:
Configure the CloudWatch registry:
Creating Meters
As mentioned before there are various types of meters for different applications. Next, I will briefly explain the most common ones, with one example of how to use them.
Example of how to use a Micrometer Counter
Now we instantiate a counter in charge of counting API calls from external integrations by integration type:
Or we could count the number of products by sale by integration type:
View Metrics
Now that we have collected metrics from different sources, such as application-level, JVM or even custom defined metrics, Micrometer will aggregate these metrics so that they are compatible with the chosen monitoring system, in our case CloudWatch. Next, it will send the aggregated metrics using the chosen monitoring system client libraries, which will store and allow us to visualize and analyze them.
Therefore, in order to watch the computed metrics on CloudWatch, once you’ve deployed your application just navigate to the console in your AWS account. Under "Metrics", you should see a list of custom metrics, including the ones you've defined in your application. You can create alarms and dashboards to monitor these metrics. It's important to note that Micrometer takes care of collecting and pushing metrics to CloudWatch or any other monitoring/observation service.
Micrometer is a powerful tool for collecting and publishing application metrics. In this document we covered how to publish custom metrics from a Spring application to Cloudwatch just by following a few steps, in order to gain insights into the performance and behavior of your applications. Moreover, by using Micrometer, we have the flexibility to publish those metrics to other analytics/monitoring services just by adding new strategies and we don't have to care about data sync'ing, which really simplifies the metric setup, configuration and provisioning.