Custom counter using prometheus not visible on /actuator/prometheus

Viewed 3245

I am trying to add custom metrics in my spring-boot application. I have looked at numerous examples and still, I'm failing to add a custom Counter.

application.properties

management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=*
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true

code

static final Counter requests = 
Counter.build().namespace("java").name("requests_total").help("Total requests.")
.register();

@CrossOrigin
@GetMapping("/test")
public int processRequest() {
    requests.inc();
    return (int) requests.get();
}

I can see the counter value increasing when I access the API. The problem is that I cannot find my newly created metrics on http://localhost:8080/actuator/prometheus and on the prometheus :9090 page. So I figure the counter is not getting registered(??). What am I missing here?

2 Answers

It looks like you are using the Prometheus Java API directly. The Counter you create is registered with the default CollectorRegistry of the Prometheus Java API but it is not registered with Micrometer as it is instantiating its own CollectorRegistry and thus your Counter is not shown there.

You should be using the Micrometer Counter API instead of directly using the Prometheus Java API. This has the added benefit that you can exchange your monitoring backend without any changes to your instrumentation code at all.

Additionally, it seems you would like to measure HTTP requests. These are usually automatically timed. Have a look for a metric family called http_server_requests_seconds_[count,sum,max] in your /actuator/prometheus endpoint.

You could do something like this. Spring will automatically find the collector registry and wire it.

@Component
public class CustomeCounter {

Counter mycounter;

public CustomCounter(CollectorRegistry registry) {
 mycounter = Counter.build().name("test").help("test").register(registry);
}

public void incrementCounter() {
 mycounter.inc();
}
}


@Component
public class Test{

@Resource
private CustomCounter customCounter;

public void testInc() {
customCounter.incrementCounter();
}
}
Related