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?


Have you tried with a basic filter like this?

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;

public class StatsFilter implements Filter {

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

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

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

    public void destroy() {
        // empty

Source: stackoverflow