Spring mvc integration with prometheus Example

In this article ,we will see how we can monitor spring MVC applications using prometheus tool . You wont get much documentation for this setup on web. Prometheus is mostly configured with spring boot easily. But in order to configure it with spring MVC based application , it requires some additional configurations –


Prometheus is a time-series monitoring application written in Go. It can run on a server, in a docker container, or as part of a Kubernetes cluster (or something similar). Prometheus collects, stores, and visualizes time-series data so that you can monitor your systems. You can tell Prometheus exactly where to find metrics by configuring a list of “scrape jobs”. Applications that are being monitored can provide metrics endpoints to Prometheus using any one of the many client libraries available; additionally, separate exporters can gather metrics from applications to make them available in Prometheus. Metrics get stored locally for 15 days, by default, and any Prometheus server can scrape another one for data. Additionally, remote storage is another option for Prometheus data – provided there is a reliable remote storage endpoint.


  • The option of “service discovery” allows Prometheus to keep track of all current endpoints effortlessly.
  • Outages are quickly detected .
  • The PromQL query language is incredibly flexible and Turing-complete.
  • There’s also a very low load on the services monitored (metrics get stored in memory as they get generated), allowing fewer resources to get used.
  • Additionally, Prometheus users can control traffic volumes, access metrics in the browser, and allow for easy reconfiguration.

Step 1 : Spring MVC application pom.xml configuration

Below prometheus dependencies are required in pom.xml for project –

<!-- Hotspot JVM metrics-->
<!-- Exposition servlet-->
<!-- Pushgateway exposition-->

Step 2 : Spring MVC application web.xml configuration

We need configure MetricsServlet to capture the metrics of our spring mvc application as below –


Step 3: Add an interceptor class

This will intercept all the requests coming to application and capture the metrics to be exposed to prometheus –

package com.myjavablog.config;

import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.Histogram;
import io.prometheus.client.Summary;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * @author anupb

public class PrometheusMetricsInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = Logger.getLogger(PrometheusMetricsInterceptor.class);

    private static final Histogram requestLatency = Histogram.build()


            .help("Request latency in seconds.")

            .labelNames("systemId", "appId", "type", "name", "method").register();

    private ThreadLocal<Histogram.Timer> timerThreadLocal;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        return super.preHandle(request, response, handler);


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        String name = this.getName(request, handler).toLowerCase();
        String method = request.getMethod().toUpperCase();

        timerThreadLocal = new ThreadLocal<>();
        timerThreadLocal.set(requestLatency.labels(name, method).startTimer());
        super.postHandle(request, response, handler, modelAndView);

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        super.afterCompletion(request, response, handler, ex);

        if (timerThreadLocal.get() != null) {

    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        super.afterConcurrentHandlingStarted(request, response, handler);

    private String getName(HttpServletRequest request, Object handler) {
        String name = "";

        try {
            if (handler != null && handler instanceof HandlerMethod) {

                HandlerMethod method = (HandlerMethod) handler;
                String className = ((HandlerMethod) handler).getBeanType().getName();
                name = className + "." + method.getMethod().getName();
            } else {
                name = request.getRequestURI();

        } catch (Exception ex) {
            logger.error("getName", ex);
        } finally {
            return name;

Step 4: Add prometheus initialization configuration

This will expose the metrics to prometheus server –

package com.myjavablog.config;
 public class PrometheusConfig {

private static Logger logger = Logger.getLogger(PrometheusConfig.class);



public void initialize() {

logger.info("prometheus init...");


logger.info("prometheus has been initialized...");



Step 5: Add an interceptor to spring-mvc.xml

You need to first add the schema location as below –



Then you need to add below tag –


<bean class="com.xx.config.PrometheusMetricsInterceptor"/>


Step 6: Add configuration to applicationcontext.xml

<bean id="prometheusConfig" class="com.myjavablog.config.PrometheusConfig" init-method="initialize" />

Once all this configuration is done , you can add the application URL in prometheus.

These parameters are useful to monitor your spring MVC application.

Close Bitnami banner