I am in the spring-boot-actuator
world mow...
How can I add my own metrics coming from a custom function from my @Service class?
I would expect to have something like
meterRegistry.registerNewGauge(
"animals_count",
"cats",
animalCounterService::countCatsFromDatabase
);
currently i can only find easy metrics like
meterRegistry.counter("animals_count").increment();
but that doesn't help much when I have to aggregate things like database entries. I need a more flexible one.
I also found something like MeterBinder.bindTo
but that didn't worked. No error, nothing in metrics.
I am searching now for months without any success.
thanks
I'm assuming you're using Micrometer for metrics, right?
If so, you can create a gauge and bind it to any object that provides a method that returns double like this:
@Service
public class MyService {
...
public double calculateValueForGauge() {...}
}
MyService service = ...// get from spring
MeterRegistry registry = ... // get from spring
// here is how you can create a gauge and bind it to an arbitrary method of your service
Gauge.builder("some.name.goes.here, service, (service) -> service.calculateValueForGauge())
.register(registry);
For example you can place the code of gauge registration to the listener that will be called when the application context is started:
@EventListener
public void onApplicationStarted(ApplicationReadyEvent event) {
// register gauges here
}