Springboot uses interceptors to print logs

Time:2021-2-23
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class);
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String userName = JWTUtil.getUsername(request.getHeader("X-Token"));
                String userId = JWTUtil.getUserId(request.getHeader("X-Token"));
                JSONObject json = new JSONObject();
                json.put("userId", userId);
                json.put("userName", userName);
                json.put("userIp", request.getRemoteAddr());
                json.put("requestInterface:", request.getRequestURI());
                json.put("param",request.getParameterMap());
//                 logger.debug ("useid: {}, username: {}, request interface: {}, request IP: {}, request parameter: {}", userid, username, request.getRequestURI ()
//                        , request.getRemoteAddr(), JSON.toJSONString(request.getParameterMap()));
                logger.info(json.toString());
                return true;
            }
        });

    }

}