How to create a metric in SpringBoot2.1.4.RELEASE?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
How to create a metric in SpringBoot2.1.4.RELEASE?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
If you're using spring-boot-starter-actuator
, a bean of type MeterRegistry
will be created. Once autowired, this allows you to create several metrics, such as counters, gauges and metrics. Each of these have a fluent builder you can use that allows you to set them up, for example:
A Counter
can be used for simple incrementing metrics, for example, the amount of times a method has been called.
Counter customCounter = Counter
.builder("my.custom.metric.counter")
.register(meterRegistry);
By using customCounter.increment()
you can increase the value.
A Gauge
on the other hand is a dynamic/live value that should be measured directly. An example of this is the size of a connection pool:
Gauge
.builder("my.custom.metric.gauge", () -> connectionPool.size())
.register(meterRegistry);
The builder allows you to pass a Supplier
to measure whatever you want.
As the name mentions, this can be used to measure the time it takes do something, for example:
Timer customTimer = Timer
.builder("my.custom.metric.timer")
.register(meterRegistry);
By using the customTimer.record(() -> myMethod())
, you can add a metric about how long it takes to invoke myMethod()
.
You should be able to access these metrics when running the application. If you want to see them through HTTP, you can enable the metrics endpoint like this:
management.endpoints.web.exposure.include=metrics # Enable metrics endpoint
After that, you should be able to visit http://localhost:8080/actuator to see the list of enabled endpoints, which should contain http://localhost:8080/actuator/metrics.
This API should return a list of available metrics, which can be accessed as http://localhost:8080/actuator/metrics/my.custom.metric.counter.
You can use micrometer:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
This will give you the end-point: /actuator/prometheus