Jobs
Blogs
Courses
Mentorship
Partners
For Employers
e2e logo

Spring Boot - Prometheus

mac

Prometheus is an open-source time-series database, which stores a sequence of data points, across time for monitoring and alerting. Prometheus is basically used to store analytics data from your applications and this allows you to perform time-series analysis of metrics. Prometheus is a standalone project, which means that it does not depend on other resources to run, like an external API or database. 

Adding Prometheus to Spring Boot

To add Prometheus to our application need to add a dependency which is Spring Boot Actuator, this exposes some APIs, for health-checking and monitoring of your apps. 

Now, we need to add the Micrometer registry dependency which specifically enables Prometheus support, because this allows the metrics collected by Micrometer to be exposed in a Prometheus way.

Next, to add a custom timer, we need to add a new dependency – the AOP dependency for Spring Boot because of the way that Micrometer times methods, it depends on AspectJ, which is provided in AOP. So our pom.xml looks like this:

Next, we need to set a few properties so that actuator will show endpoints appended to our application URL:

Now, we need to register the  TimedAspect bean in our Spring context to allow Micrometer to add a timer to our custom methods.

Then, find the method that you want to time, and add the @Timed annotation to it.  After that add the value attribute to give the metric a name. Like below example:

Now let's check it out by starting our application and hitting endpoint “/home”. We will access the Prometheus endpoint in actuator like this:

Now will we access this endpoint and will check the entry of our method:

This is how we will check the health of our application/method etc.

Matrix types and their use case

Gauge: Measuring resource usage, capacity, etc. Values that can rise and fall, and that have fixed upper bounds. Examples like the size of a collection, number of running threads, number of messages on a queue, memory usage.

Counter: Measuring the number of events or actions - a value that only increases, and never decreases. The total number of orders processed, total tasks completed, etc.

Timer: Measuring short-duration events and their frequency. Examples like method execution time, request duration, time is taken to make a cup of tea.

If you think there is some mistake in this article feel free to comment on it.