Spring Boot 2.0 Projects
上QQ阅读APP看书,第一时间看更新

Custom metrics using Micrometer

With the introduction of Micrometer to Spring Boot Actuator in Spring Boot 2.0, metrics can be customized easily. The following code snippet from CustomEndpointWebExtension shows how to make use of io.micrometer.core.instrument.MeterRegistry to maintain a counter with the name custom.endpoint.calls, which will be incremented every time CustomEndpointWebExtension is invoked:

public static final String CUSTOM_ENDPOINT_CALLS = "custom.endpoint.calls";

private final MeterRegistry meterRegistry;

public CustomEndpointWebExtension(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}

@ReadOperation
public WebEndpointResponse<String> getWeb() {
meterRegistry.counter(CUSTOM_ENDPOINT_CALLS).increment();
return new WebEndpointResponse<>("Custom Web Extension Hello, World!", 200);
}

The preceding code injects MeterRegistry from the Micrometer Framework, which is used to create and retrieve a counter named custom.endpoint.calls and increment it during each read operation of the custom web endpoint extension.

This metric will be available under the http://<host>:<port>/actuator/metrics/custom.endpoint.calls URL, which will show a result similar to the following:

{  
"name":"custom.endpoint.calls",
"measurements":[
{
"statistic":"COUNT",
"value":3.0
}
],
"availableTags":[ ]
}