Micrometer and Prometheus to monitor Spring Boot application
Setup
As mentioned, we shall set up 3 things
- Spring Boot application
- Micrometer to expose actuator metrics in Prometheus format
- Prometheus to store and make sense of metrics
Setup SpringBoot application
Create an endpoint that you would like to play with. I added a chance endpoint that looks like this:
@RestController
@RequestMapping("/chance")
public class ChanceController {
@GetMapping
public ResponseEntity chances() {
double dChance = Math.random() * 10;
int chance = (int) dChance;
System.out.println("Chance: " + dChance);
if(chance <= 7) {
return new ResponseEntity("Success", HttpStatus.OK);
} else if(chance == 8) {
return new ResponseEntity("Failure", HttpStatus.UNAUTHORIZED);
} else {
return new ResponseEntity("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
This endpoint has an 80% chance of success, 10% chance of 401 (Unauthorized) response, and 10% chance of 500 (Internal Server Error) response.
Now our spring boot application is good to go.
Check the endpoints exposed at localhost:8080/actuator.
Setup micrometer
Micrometer can be thought of as middleware or an adapter. It converts Spring Boot's actuator metrics in a format that can be read by any metric collection tool. Prometheus is one such tool it supports. For a complete list, refer to this documentation.
So we add a dependency to micrometer-registry-prometheus. e.g.
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Now restart the spring boot app. A new endpoint is created that exposes metrics in a format that Prometheus can understand. This endpoint is http://localhost:8080/actuator/prometheus.
Setup Prometheus
global:external_labels:monitor: 'codelab-monitor'scrape_configs:- job_name: 'spring_boot_project'scrape_interval: 5smetrics_path: '/actuator/prometheus'static_configs:- targets: ['docker.for.mac.host.internal:8080']
Notice the targets. Ideally, I would have used 'localhost'. However 'localhost' would refer to the docker container. I wish to point to my laptop. On mac, you can do this as 'docker.for.mac.host.internal'. On windows, you can do this as 'host.docker.internal'. In summary - refer to your docker documentation. Or stackoverflow.
Also 'metrics_path' points to the new actuator endpoint added by the multimeter.
View metrics
http_server_requests_seconds_count{method="GET", uri="/chance"}
My graph looks like this:
Explaining prometheus query language and usage of Prometheus is beyond scope of this article.
Comments
Post a Comment