aop+自定义注解实现打印参数日志-简易版

aop+自定义注解实现打印接口出入参数

1:自定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodLog {

    int type() default 0; //0:打印全部参数, 以及返回结果 2:打印入参

}
  1. 运行时注解
  2. 作用域为方法上
  3. 注解参数: 0:打印入参+返回结果 1: 只打印入参
2: aop实现拦截注解打印参数
@Aspect
@Component
@Slf4j
public class MethodLogAspect {

    @Pointcut("@annotation(cn.ssk.model.annotation.MethodLog)")
    public void pointCut(){}


    @AfterReturning(value = "pointCut()",returning = "result")
    public void afterReturn(JoinPoint joinPoint,Object result){

        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            MethodLog annotation = method.getAnnotation(MethodLog.class);
            if (Objects.isNull(annotation)){
                return;
            }
            String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
            log.error("方法名:"+methodName);
            int type = annotation.type();
            Object[] args = joinPoint.getArgs();
            log.info("入参:");
            log.info(JSON.toJSONString(args));
            if (type == 0){
                log.info("返回结果:");
                log.info(JSON.toJSONString(result));
            }
        } catch (Exception e) {
            log.error("MethodLogAspect.afterReturn error",e);
        }
    }
}

  1. AfterReturning: 在方法return之前进入此aop, 可拿到该方法参数, 返回值等信息
  2. 通过JoinPoint 可拿到方法名, 注解, 参数
  3. 最后打印到log日志系统中
测试
  1. 注解作用于service
    在这里插入图片描述
  2. postman参数
    在这里插入图片描述
  3. 服务器打印参数
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值