springBoot过滤器-打印接口执行时间

springBoot过滤器-打印接口执行时间日志

1 继承过滤器接口,过滤器是放在容器里面使用(tomcat)Filter ,重写init和doFilter方法
2.使用日志工厂LoggerFactory创建日志实体
3.HttpServletRequest 里面有请求信息,如请求头,请求地址,请求主机等。
4.filterChain.doFilter是去调用业务方法

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LogFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(LogFilter.class);

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

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 打印请求信息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        LOG.info("------------- LogFilter 开始 -------------");
        LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
        LOG.info("远程地址: {}", request.getRemoteAddr());

        long startTime = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        LOG.info("------------- LogFilter 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
    }
}

springBoot过滤器-打印接口执行时间_第1张图片

你可能感兴趣的:(Java,springBoot,java,springBoot过滤器)