谁在什么时间做了什么事情,产生了什么结果
LogAdvance.java
@Slf4j
@Component
@Aspect
public class LogAdvance {
//切入点 r..*.*(..))对所有的进行日志
@Pointcut("execution(* com.hc.controller..*.*(..))")
public void logPointcut() {
}
//后置增强,进入后一个日志
//要想使用先用注解注入
@After("logPointcut()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] params = joinPoint.getArgs();
System.out.print(methodName + " " + Arrays.toString(params));
//记录日志
log(methodName, params, "");
}
private void log(String methodName, Object[] params, String result) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();//获取传递的参数值
User user = (User) request.getSession().getAttribute(WeGoConst.SESSION_USER);
Long userId = null;
if(user!=null){
userId = user.getId();
}
//TODO: 获取用户的真实IP
String ip = "";
//使用日志
log.info(new LogBean(userId,"", methodName,Arrays.toString(params),ip, LocalDateTime.now(), result).toString());
}
//返回增强
@AfterReturning(pointcut = "logPointcut()", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, int result) {
String methodName = joinPoint.getSignature().getName(); //获取方法名
Object[] params = joinPoint.getArgs(); //获取参数列表
System.out.print(methodName + " " + Arrays.toString(params) + " " + result);
//记录日志
log(methodName, params, result + "");
}
//异常增强
@AfterThrowing(pointcut = "logPointcut()", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, ArithmeticException ex) { //---①
String methodName = joinPoint.getSignature().getName();
Object[] params = joinPoint.getArgs();
System.out.print(methodName + " " + Arrays.toString(params) + " " + ex);
//记录日志
log(methodName, params, ex.getMessage());
}
}