spring 自定义注解+AOP 打印任务日志

2022-07-03  本文已影响0人  饱饱想要灵感
  1. 新增注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TaskLog {
    /** 任务名称 */
    String taskName();
    /** 入参 */
    boolean isLogParam() default true;
    /** 结果 */
    boolean isLogResult() default true;
    /** 时长 */
    boolean isLogDuration() default true;

}
  1. 切面控制
@Aspect
@Component
public class TaskLogAopConfig {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Around("@annotation(taskLog)")
    public Object taskControl(ProceedingJoinPoint proceedingJoinPoint, TaskLog taskLog) {

        try {
            String startMsg = taskLog.taskName() + ",开始...";
            if (taskLog.isLogParam()) {
                Object[] argValues = proceedingJoinPoint.getArgs();
                if (ObjectUtil.isNotNull(argValues)) {
                    CodeSignature codeSignature = (CodeSignature) proceedingJoinPoint.getSignature();
                    String[] parameterNames = codeSignature.getParameterNames();
                    Map<String, Object> paramMap = Maps.newLinkedHashMap();
                    for (int i = 0; i < parameterNames.length; i++) {
                        paramMap.put(parameterNames[i], argValues[i]);
                    }
                    startMsg += "入参:" + JSONUtils.toJSONString(paramMap);
                }
            }
            logger.info(startMsg);

            long start = System.currentTimeMillis();
            Object result = proceedingJoinPoint.proceed();

            String endMsg = taskLog.taskName() + ",结束.";
            if (taskLog.isLogDuration()) {
                endMsg += "耗时:" + DateUtil.totalSpend(start, System.currentTimeMillis()) + ".";
            }
            if (taskLog.isLogResult() && ObjectUtil.isNotNull(result)) {
                endMsg += "返回结果:" + JSONUtils.toJSONString(result);
            }
            logger.info(endMsg);

            return result;
        } catch (Throwable throwable) {
            logger.error("{},失败!", taskLog.taskName(), throwable);
            throw new RuntimeException(throwable);
        }
    }
}

附耗时计算代码

    public static String totalSpend(long time1, long time2){
        double totalSecond = Math.abs(time2 - time1) / 1000.0;
        double minutes = totalSecond / 60;
        double seconds = totalSecond % 60;
        if (totalSecond <= 0.1) {
            return "0.1秒";
        }

        String total = "";
        if (minutes>=1) {
            total += String.format("%.0f分钟", minutes);
        }
        if (seconds>=1) {
            total += String.format("%.0f秒", seconds);
        }
        if (ObjectUtil.isNull(total)) {
            total = String.format("%.1f秒", seconds);
        }
        return total;
    }
上一篇下一篇

猜你喜欢

热点阅读