Use Micrometer Observation API with a non Spring app

114 Views Asked by At

I would like to use the new Micrometer Observation API with a non Spring app: is it possible ?

I am trying to find a way to get the instance of the ObservationRegistry object used in a specific class from another class (a servlet basically to expose an endpoint and scrape).

With PrometheusMeterRegistry, I used to do:

    public class AppMonitoringServlet
    extends HttpServlet
{
    private final PrometheusMeterRegistry registry = new PrometheusMeterRegistry( PrometheusConfig.DEFAULT );
    
    @Override
    public void init( ServletConfig config )
    {
        // Some stuff here...

        Metrics.addRegistry( registry ); // Add my custom registry to the global registry
    }

    @Override
    protected void doGet( final HttpServletRequest req, final HttpServletResponse resp )
        throws ServletException, IOException
    {
        resp.setStatus( HttpServletResponse.SC_OK );
        String contentType = TextFormat.chooseContentType( req.getHeader( "Accept" ) );
        resp.setContentType( contentType );

        try (Writer writer = new BufferedWriter( resp.getWriter() ))
        {
            writer.write( registry.scrape( contentType ) ); // Scrape the metrics
            writer.flush();
        }
    }
}

Can I use the same kind of logic to get Observation metrics? Is there an Observation global registry?

1

There are 1 best solutions below

0
On BEST ANSWER

I would like to use the new Micrometer Observation API with a non Spring app: is it possible ?

Absolutely, Micrometer does not have any Spring dependencies, you can use it with any frameworks or without a framework (fyi: Micronaut already supports the Observation API and Quarkus is working on it).

I am trying to find a way to get the instance of the ObservationRegistry object used in a specific class from another class

You can inject the ObservationRegistry to your components through a constructor or setters.

a servlet basically to expose an endpoint and scrape

I'm not sure why you need an ObservationRegistry there, you can inject the same PrometheusMeterRegistry instance to this servlet what you registered into your DefaultMeterObservationHandler.

Can I use the same kind of logic to get Observation metrics? Is there an Observation global registry?

I'm not sure what you mean by "Observation metrics". There is no global Observation registry and we are not planning to add one right now. If you want one (I would strongly advise against it), you can create a public static final singleton instance and use that everywhere.