Ivan Cachicatari
Ivan Cachicatari

Reputation: 4284

Jersey log all response times for services

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?

Upvotes: 5

Views: 4247

Answers (2)

Ivan Cachicatari
Ivan Cachicatari

Reputation: 4284

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");        
}

Upvotes: 2

mystarrocks
mystarrocks

Reputation: 4088

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.

Upvotes: 6

Related Questions