1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| @Aspect @Component @Slf4j public class TimerPrinter { private static final ThreadLocal<Long> TIMER_LONG_LOCAL=new ThreadLocal<Long>(){ protected Long initValue(){ return System.currentTimeMillis(); } };
@Pointcut("@annotation(com.example.demo.aop.TimerLog)") public void pointCut(){
} @Before("pointCut()") public void before(JoinPoint joinPoint){ Signature signature = joinPoint.getSignature(); TimerPrinter.start(signature.getDeclaringTypeName(),signature.getName()); }
@Around("pointCut()") public void around(){
} @AfterReturning(pointcut = "pointCut()") public void after(JoinPoint joinPoint){ Signature signature = joinPoint.getSignature(); TimerLog annotation = ((MethodSignature)signature).getMethod().getAnnotation(TimerLog.class); TimerTypeEnum typeEnum = annotation.type(); TimerPrinter.end(signature.getDeclaringTypeName(),signature.getName(),typeEnum); }
public static final void start(String className,String methodName) { TIMER_LONG_LOCAL.set(System.currentTimeMillis()); log.info("[{}]-[{}] start...",className,methodName); } public static final void end(String className,String methodName){ log.info("[]-[] total use time: [{}]{}",className,methodName,buildTime(null),TimerTypeEnum.MILL_SECOND.value); TIMER_LONG_LOCAL.get().intValue(); } public static void end(String className,String methodName,TimerTypeEnum timerTypeEnum){ log.info("[]-[] total use time: [{}]{}",className,methodName,buildTime(timerTypeEnum),TimerTypeEnum.MILL_SECOND.value); TIMER_LONG_LOCAL.get().intValue(); } public static Long buildTime(TimerTypeEnum typeEnum){ Long useTime = 0L; Long totalTime = System.currentTimeMillis()-TIMER_LONG_LOCAL.get(); if(null == typeEnum){ useTime = totalTime; }else if(Objects.equals(typeEnum,TimerTypeEnum.SECOND)){ useTime = totalTime/1000; }else if(Objects.equals(typeEnum,TimerTypeEnum.MINUTE)){ useTime = totalTime/6000; } return useTime; } }
|