Home > OS >  Add Prometheus Metrics Endpoint to Java App Using Jax-Rs
Add Prometheus Metrics Endpoint to Java App Using Jax-Rs

Time:11-07

I’m trying to add a Prometheus metrics exporter to my Java app. The app is currently using javax.ws.rs to define REST endpoints.

For example:

Import javax.ws.rs.*; 
Import javax.ws.rs.core.MediaType; 
Import javax.ws.rs.core.Response;

@GET
@Path(“/example”)
@Timed 
Public Response example(@QueryParam(“id”) Integer id) { 
   return Response.ok(“testing”)
}

All the examples I found for setting up Prometheus in Java are using Spring. They suggest the following:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.prometheus.client.exporter.HTTPServer;
import java.io.IOException;  

@SpringBootApplication 
public class App {  
   public static void main(String[] args) { 
      SpringApplication.run(App.class, args);  
      try { 
          HTTPServer server = new HTTPServer(8081);
      } catch (IOException e) { e.printStackTrace(); } 
   }  
}

Is there a way I can simply define a new endpoint in my current setup, for example:

@GET
@Path(“/metrics”)
@Timed 
Public Response example { 
   return Response.ok(“return prom metrics here”)
}

Without having to introduce Spring into the stack?

CodePudding user response:

This can be done as follows:

import io.prometheus.client.Counter; 
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.TextFormat;

CollectorRegistry registry = new CollectorRegistry(); 

Counter exCounter = Counter.build().name(“example”).register(registry);

@GET
@Path(“/metrics”)
Public String getMetrics() { 
  Writer writer = new StringWriter(); 
  try { 
     TextFormat.write004(writer, registry.metricFamilySamples()); 
     return writer.toString(); 
  } catch (IOException e) { 
     return “error”;
  }
}
  • Related