SpringBoot使用拦截器打印日志

66次阅读

共计 954 个字符,预计需要花费 3 分钟才能阅读完成。

@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:{}, 申请接口:{},申请 IP:{},申请参数:{}",userId,userName,request.getRequestURI()
//                        , request.getRemoteAddr(), JSON.toJSONString(request.getParameterMap()));
                logger.info(json.toString());
                return true;
            }
        });

    }

}

正文完
 0