Search code examples
springspring-bootspring-cloudnetflix-zuul

Measure the time in which a request is sent to zuul proxy


I have multiple microservices made in spring boot which communicates with a zuul proxy.My problem is that the requests are taking too much time and i would like to measure the time spent from when the request gets to the proxy and the time in which the request gets forwarded from the proxy to my microservices.Are there any ways to do this? Thanks!


Solution

  • Other approach similar to this can be done with ZuulFilter. Below code was written without checking it so there can be some errors but it should show the idea. First add Pre filter

    public class PreFilter extends ZuulFilter {
    
        private static final Logger logger = LoggerFactory.getLogger(PreFilter.class);
    
        @Override
        public int filterOrder() {
            return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration
        }
    
        @Override
        public String filterType() {
            return PRE_TYPE;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
        @Override
        public Object run() {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
            long startTime = Instant.now().toEpochMilli();
            logger.info("Request URL::" + request.getRequestURL().toString() +
            ":: Start Time=" + Instant.now());
            ctx.put("startTime", startTime);
            return null;
        }
    }
    

    Then in Post filter

    public class PostFilter extends ZuulFilter {
    
        private static final Logger logger = LoggerFactory.getLogger(PostFilter.class);
        @Override
        public String filterType() {
            return POST_TYPE;
        }
    
        @Override
        public int filterOrder() {
            return SEND_RESPONSE_FILTER_ORDER - 1;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
            long startTime = (Long) ctx.get("startTime");
    
            logger.info("Request URL::" + request.getRequestURL().toString() +
       ":: Time Taken=" + (Instant.now().toEpochMilli() - startTime));
            return null;
        }
    }