5

I have a Java application and I want to log all execution times for each REST service.

How to measure execution time for each request? How the filter will be configured?

Ivan Cachicatari
  • 4,212
  • 2
  • 21
  • 41

2 Answers2

6

Jersey event listeners must be what you're after.

There are two flavors of such event listeners as mentioned in their docs on monitoring and tracing:

  • ApplicationEventListener for listening to application events, and
  • RequestEventListener for listening to events of request processing

Only the first type, ApplicationEventListener can be directly registered as an application-wide provider. The RequestEventListener is designed to be specific to every request and can be only returned from the ApplicationEventListener as such.

mystarrocks
  • 4,040
  • 2
  • 36
  • 61
  • What packages would be? I have available this: com.sun.jersey.spi.monitoring.RequestListener – Ivan Cachicatari Nov 12 '14 at 00:19
  • I've also adopted this aproach. Implement both listeners seems to be the most suitable solution. Packages for Jersey 2.* are org.glassfish.jersey.server.monitoring – Sergio Gabari Jun 16 '16 at 09:57
  • If you click on the user guide in the link provided in this answer and check (at the time of this comment) Example 22.2. Request event listener you will see an example on how to get the time it took to complete the request. – Omar Abdel Bari Jun 13 '19 at 18:53
2

I added a filter to all service requests an it works fine:

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain p_filterChain) throws IOException, ServletException {


    long startTime = System.currentTimeMillis();
    String url = "unknown"; 
    if (request instanceof HttpServletRequest) {
         url = ((HttpServletRequest)request).getRequestURL().toString();
         String queryString = ((HttpServletRequest)request).getQueryString();
         if(queryString != null)
             url += "?" + queryString;
    }


    p_filterChain.doFilter(request, response);

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;

    LogManager logm = new LogManager();
    logm.newLog(url,elapsedTime);
    System.out.println("Request: " + url + "  " + elapsedTime + "ms");        
}
Ivan Cachicatari
  • 4,212
  • 2
  • 21
  • 41