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);
}
}
}