SpringBoot使用过滤器打印接口请求信息

话不多说,直接贴代码~

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;

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

/**
 * 打印请求信息
 */
@Configuration
public class StatisticsFilter implements Filter {
    private static Log log = LogFactory.getLog(StatisticsFilter.class);

    public StatisticsFilter() {
    }

    public void destroy() {
    }

    public void init(FilterConfig arg0) {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url = httpRequest.getRequestURI();
        long startTime = System.currentTimeMillis();
        boolean var20 = false;

		// 此方式支持form-data传参方式参数获取,其他传参方式请自行研究
        Map<String, String[]> parameterMap = httpRequest.getParameterMap();
        List<String> parameterList = new ArrayList<>();
        parameterMap.forEach((key, value) -> {
            parameterList.add(key + ":" + Arrays.toString(value));
        });

        try {
            var20 = true;
            chain.doFilter(request, response);
            var20 = false;
        } finally {
            if (var20) {
                long var14 = System.currentTimeMillis();
                long time = var14 - startTime;
                String clientIp = httpRequest.getHeader("x-forwarded-for");
                if (clientIp == null) {
                    clientIp = httpRequest.getRemoteAddr();
                }

                log.info("客户端IP:" + clientIp + "" + ", 请求地址:" + url + ", 请求参数:{" + String.join(",", parameterList) + "}, 响应时间:" + time + "ms");
            }
        }

        long timeConsuming = System.currentTimeMillis() - startTime;
        String clientIp = httpRequest.getHeader("x-forwarded-for");
        if (clientIp == null) {
            clientIp = httpRequest.getRemoteAddr();
        }

        log.info("客户端IP:" + clientIp + "" + ", 请求地址:" + url + ", 请求参数:{" + String.join(",", parameterList) + "}, 响应时间:" + timeConsuming + "ms");
    }
}

控制台打印:
在这里插入图片描述

你可能感兴趣的:(SpringBoot,filter,日志)