项目中日志增强

谁在什么时间做了什么事情,产生了什么结果
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());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值