CommonsRequestLoggingFilter监控请求

 很多时候我们都是使用AOP的方式来打log的,今天发现spring下面有一个filter也是蛮好用的,可以给你想拦截的请求定制log。

1. 可以设置请求体里哪些内容可以被log

2. shouldLog判断时候可以log ,定制log前缀后缀

3. beforeRequest, afterRequest重写请求前后log的信息

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;


@Configuration
public class CalendarLoggingFilter extends CommonsRequestLoggingFilter {

    private final Logger logger = LoggerFactory.getLogger(CalendarLoggingFilter.class);
    private static long beforeTime;
    private static long afterTime;

    public MyDeskCalendarLoggingFilter(){
        super.setIncludeClientInfo(false);
        super.setIncludeHeaders(false);
        super.setIncludePayload(true);
        super.setMaxPayloadLength(2000);
        super.setIncludeQueryString(true);
        
    }

    @Override
    protected boolean shouldLog(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        // Checks if request matches /api/calendarCompletionDate
        boolean shouldLog = requestURI.matches("^/api\\/calendarCompletionDate$");

        if (shouldLog) {
            long currentUserId = SecurityUtils.getCurrentAccountUserId();
            String method = request.getMethod();
            super.setBeforeMessagePrefix("Before request [" + method + "," + "currentUserId:" + currentUserId + ","); //Default is just Before request
            super.setAfterMessagePrefix("After request [" + method + "," + "currentUserId:" + currentUserId + ",");   //Default is just After request
        }
        return shouldLog;
    }

    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {
        beforeTime = System.currentTimeMillis();
        MemoryLogUtil.logUsed("beforeRequest");//only shows at this moment in time
        super.beforeRequest(request, message);
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {
        afterTime = System.currentTimeMillis();
        logger.info("afterRequest: Time taken: " + (afterTime-beforeTime) + " in milliseconds");
        MemoryLogUtil.logUsed("afterRequest");//only shows at this moment in time
        super.afterRequest(request, message);
    }
}

你可能感兴趣的:(spring)