自定义注解打印日志与耗时

        在项目执行中针对一些方法需要重复增加log与耗时打印等,此处用Spring Aop环绕增强实现。非常简单,步骤如下:

1、自定义注解

@Documented //注解修饰会被Javadoc处理,注解会在文档中生成
@Target(ElementType.METHOD)//定义注解作用范围,参考ElementType枚举,此处作用在方法上
@Retention(RetentionPolicy.RUNTIME)//定义注解生命周期,参考RetentionPolicy枚举,此处参与代码逻辑
@Inherited//定义注解是否可以被继承,此处酌情处理
public @interface LogMsg {

    //自定义方法名称,默认为方法名
    String name();
}

2、定义切面类

@Slf4j//log相关
@Component//作为组件交给spring管理
@Aspect//定义为切面类
public class LogMsgAop {

    //定义切点,此处以注解为切点
    @Pointcut("@annotation(com.hs.LogMsg)")
    public void logPoint() {
    }

    //定义环绕增强作用在定义好的切点处
    @Around("logPoint()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature pointSignature = (MethodSignature) joinPoint.getSignature();
        Method method = pointSignature.getMethod();
        LogMsg annotation = method.getAnnotation(LogMsg.class);
        //获取注解中的name或者方法名
        String msgPre = StringUtils.isBlank(annotation.name()) ? method.getName() : annotation.name();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = pointSignature.getParameterNames();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parameterNames.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(parameterNames[i]);
            sb.append(":");
            sb.append(args[i]);
        }
        log.info("{}方法入参:{}", msgPre, sb.toString());
        long start = System.currentTimeMillis();
        //默认执行方法
        Object result = joinPoint.proceed(args);
        log.info("{}方法出参:{},耗时:{}ms", msgPre, result, System.currentTimeMillis() - start);
        return result;
    }
}

3、在需要打印日志的方法上使用

@LogMsg(name = "这是一个测试方法")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值