简体   繁体   English

Jersey记录服务的所有响应时间

[英]Jersey log all response times for services

I have a Java application and I want to log all execution times for each REST service. 我有一个Java应用程序,我想记录每个REST服务的所有执行时间。

How to measure execution time for each request? 如何衡量每个请求的执行时间? How the filter will be configured? 如何配置过滤器?

Jersey event listeners must be what you're after. 泽西event listeners必须是你所追求的。

There are two flavors of such event listeners as mentioned in their docs on monitoring and tracing: 在他们关于监视和跟踪的文档中提到了两种这样的event listeners

  • ApplicationEventListener for listening to application events, and ApplicationEventListener用于侦听应用程序事件,以及
  • RequestEventListener for listening to events of request processing RequestEventListener用于侦听请求处理的事件

Only the first type, ApplicationEventListener can be directly registered as an application-wide provider. 只有第一种类型的ApplicationEventListener可以直接注册为应用程序范围的提供者。 The RequestEventListener is designed to be specific to every request and can be only returned from the ApplicationEventListener as such. RequestEventListener旨在特定于每个请求,并且只能从ApplicationEventListener返回。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM