quarkusmicroprofile

How to programatically reset all metrics in a Quarkus app using Microprofile?


I'm exposing some custom metrics from my Quarkus application using microprofile MetricRegistry class. Those metrics are consumed and exposed to Prometheus through the /metrics endpoint.

For testing purposes I'd like to reset/clear all metrics during the tearDown() part of the test. I don't mind creating a REST endpoint, that'll only be available under the test profile, to clear these metrics via an API call.

I couldn't find how to achieve that on the internet so far, does anybody have any idea on how to do that?


Solution

  • I think I have found an alternative, it's just a matter of exposing the following API:

    package com.operation;
    
    import javax.enterprise.context.ApplicationScoped;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import org.eclipse.microprofile.metrics.MetricRegistry;
    
    
    @Path("/")
    @ApplicationScoped
    @IfBuildProfile("functional")
    public class MetricReset {
    
        MetricRegistry metricRegistry;
    
        public MetricReset(MetricRegistry metricRegistry) {
            this.metricRegistry = metricRegistry;
        }
    
        @GET
        @Path("/clearmetrics")
        @Produces({ MediaType.TEXT_PLAIN })
        public Response clearAllPollerMetrics() {
            metricRegistry.removeMatching((id, metric) -> id.getName().contains("custometric"));
            return Response.ok().build();
        }
    }
    
    

    and later on calling this endpoint before each functional test:

    //...
        @BeforeEach
        public void setUp() {
            utils.resetAll();
            ClientBuilder.newClient()
                    .target("http://localhost:8080/clearmetrics")
                    .request()
                    .get();
        }
    //...