How to log time taken by Rest web service in Spring Boot?

Tags: , , ,



I am writing a web Rest web service using Spring Boot.

I want to log time taken by my webservice to process request. Also I want to log headers,method and URI called.

I have done similar in my jersey web service few months back using ContainerRequestFilter and ContainerResponseFilter filter() method.

Also, AOP is Better or Filter?

Answer

Have you tried with a basic filter like this?

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@WebFilter("/*")
public class StatsFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(StatsFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // empty
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        long time = System.currentTimeMillis();
        try {
            chain.doFilter(req, resp);
        } finally {
            time = System.currentTimeMillis() - time;
            LOGGER.trace("{}: {} ms ", ((HttpServletRequest) req).getRequestURI(),  time);
        }
    }

    @Override
    public void destroy() {
        // empty
    }
}


Source: stackoverflow