Now that we have our sample application working it’s time to add some Prometheus instrumentation to it. We will be adding support for two metrics types Counter and Histogram to our sample application. First off all we need to include the standard Prometheus libraries for Spring Boot to the dependency list and for that we will be adding the following lines in the pom.xml file

As we have our pom.xml file ready now, let’s go ahead and add the support for the Prometheus metrics in our code.

To enable the support for Counter and Histogram metrics we have to first import the required libraries

and then create both the metric types

Once created these metric types will be shared through all instances of the object. This will provide the metric a name and will add some additional HELP and TYPE text with those metrics. Now to start using the Counter metric type all we need to do is call the inc() method whenever we want to increment the metric’s count by one. Since the Histogram metric sample observations and is often used to monitor things like request latency or request sizes therefore it is used around a try...finally block as below

Now that the setup is done let’s build the jar using Maven through mvn clean package and execute the newly built jar. If we visit http://localhost:8080/ you’ll see Hello World!, and on http://localhost:8080/prometheus you can see the metrics that are currently being published by our application.

Note: As Prometheus takes advantage of Spring Boot actuator to gather and publish the metrics. Therefore, we will have to disable the default Spring Boot security and you will notice that apart from the metrics we explicitly defined in our application additional JVM metrics are also being published.

This content was originally published here.