Prometheus Integration - Java Client - Part 1

Prometheus Integration - Java Client 


For maven applications add the following lines in the pom file.

<!-- Prometheus start -->
    <!-- The client -->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient</artifactId>
        <version>${prometheus.version}</version>
    </dependency>
    <!-- Hotspot JVM metrics -->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_hotspot</artifactId>
        <version>${prometheus.version}</version>
    </dependency>
    <!-- Exposition servlet -->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_servlet</artifactId>
        <version>${prometheus.version}</version>
    </dependency>
    <!-- Prometheus end -->

For a spring-web application 

In the web.xml create the following servlet mapping

   <servlet>
        <display-name>PrometheusMetricsServlet</display-name>

        <servlet-name>PrometheusMetricsServlet</servlet-name>
        <servlet-class>io.prometheus.client.exporter.MetricsServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>PrometheusMetricsServlet</servlet-name>
        <url-pattern>/metrics</url-pattern>
   </servlet-mapping> 
You can write a filter class that will process all incoming request - url patter /*

<filter>
    <filter-name>MetricsFilter</filter-name>
    <filter-class>com.ola.accounting.dp.filters.MetricsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MetricsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Add the below line in the init method helps track JVM related metrics :

DefaultExports.initialize();
This will expose /metrics which prometheus will scrape at the interval specified in the prometheus yml file.

The following needs to be mentioned in the prometheus.yml file. This config ensure that prometheus scrapes data from the specified path at the specified interval. 

  1. Scrape interval 
  2. The metrics path 
  3. And the target hostname 
There are several metrics types in prometheus one of these can be used based on the use case.
  1. Counter
  2. Gauge
  3. Summary 
  4. Histogram

Counter

Counter to track request count exceptions success and failure rates in API calls 

// Counter
Register the counter in the init method 
requests = Counter.build().name("requests_total").help("Total requests")
.register();

incerment the counter  in the do filter
requests.inc();

Comments