Spring Boot使用拦截器日志记录

pom

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.57</version>
</dependency>

拦截器配置

@Configuration
public class LoggerWebAppConfig extends WebMvcConfigurationSupport {
    @Autowired
    private LoggerInterceptor interceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截url配置
        //registry.addInterceptor(interceptor).addPathPatterns("/**");
        // 排除url配置
        registry.addInterceptor(interceptor).excludePathPatterns("/**/get**");
    }

}

日志拦截器

@Component
public class LoggerInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
    @Autowired
    LogRepository logRepository;
    @Autowired
    AccountRepository accountRepository;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     *  请求结束后,将请求的日志保存到数据库
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long start = System.currentTimeMillis();

        JSONObject userInfo = (JSONObject)request.getSession().getAttribute("user_info");
        // 查看是否有session,只记录有session的日志
        if(userInfo!=null){

            JSONObject logger = new JSONObject();
            logger.put("user_id",userInfo.get("user_Id").toString());
            logger.put("user_name",userInfo.get("user_name").toString());
            logger.put("path",request.getRequestURI());
            logger.put("create_time",new Date());
            logger.put("method",request.getMethod());
            logger.put("param",request.getParameterMap());
            log.info(logger.toJSONString());//控制台打印

			//保存到数据库
			Log l=new Log();
            String action = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
            System.out.println(action);
            if (action.contains("edit")){
                action="修改";
            }else if (action.contains("add")){
                action="新增";
            }else if(action.contains("del")){
                action="删除";
            }
            Account account= accountRepository.findByAccount(userInfo.get("user_Id").toString());
            l.setUserId(userInfo.get("user_Id").toString());
            l.setUserName(userInfo.get("user_name").toString());
            l.setMethod(request.getMethod());
            l.setPath(request.getRequestURI());
            l.setCreateTime(new Date());
            l.setParam(JSONObject.toJSONString(request.getParameterMap()));
            l.setRole(account.getRoleName());
            l.setAction(action);
            logRepository.save(l);
            //记录消耗的时间
            log.info("save log cost={}",System.currentTimeMillis() -start);

        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值