之前写过一次关于使用aop记录日志的,不过那个基于注解实现的,也就是自定义实现日志记录,今天处理一下全局日志记录,原理和上次的相同,稍加改动即可,先看效果
上代码
@Autowired
HttpServletRequest request;
@Autowired
SysGlobalLogMapper sysGlobalLogMapper;
@Pointcut("execution(* nyist.com.project.controller..*.*(..))")
public void aspect() {
}
@Before("aspect()")
public void before(JoinPoint joinPoint) throws NoSuchMethodException, SecurityException{
SysGlobalLog sysGlobalLog = new SysGlobalLog();
sysGlobalLog.setUri(request.getRequestURI());//等同于String methodName = joinPoint.getSignature().getName();
sysGlobalLog.setType(request.getMethod());
sysGlobalLog.setMethod(joinPoint.getSignature().toString());
sysGlobalLog.setIp(request.getRemoteAddr());
sysGlobalLog.setParams(getRequestParams(joinPoint));
sysGlobalLog.setCreateTime(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()));
//sysGlobalLog.setResults(results);
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
User loginUser = (User)session.getAttribute("loginUser");
if(loginUser!=null){
sysGlobalLog.setUserId(loginUser.getId());
sysGlobalLog.setUserName(loginUser.getAccount());
}
sysGlobalLogMapper.insertSelective(sysGlobalLog);
}
//@PathVariable以及@RequestParam注解传递的参数无法打印出参数名,同时处理一下文件对象
private String getRequestParams(JoinPoint joinPoint) {
Map<String, Object> requestParams = new HashMap<>();
//参数名
String[] paramNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
//参数值
Object[] paramValues = joinPoint.getArgs();
for (int i = 0; i < paramNames.length; i++) {
Object value = paramValues[i];
//如果是文件对象
if (value instanceof MultipartFile) {
MultipartFile file = (MultipartFile) value;
value = file.getOriginalFilename(); //获取文件名
}
requestParams.put(paramNames[i], value);
}
return requestParams.toString();
}