在Spring的Java程序中,每个方法写一句log来记录这个方法执行多久是一件很恶心的事情。记录下使用annotation来解决。
1. 定义一个annotation
@Target({java.lang.annotation.ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogExecuteTime {
}
2. 然后写一个Aspect:
@Aspect
@Component
public class LogTimeInterceptor {
private static Logger logger = LoggerFactory.getLogger(LogTimeInterceptor.class);
@Pointcut("@annotation(com.xxx.quartz.cluster.annotation.LogExecuteTime)")
public void logTimeMethodPointcut() {
}
@Around("logTimeMethodPointcut()")
public Object interceptor(ProceedingJoinPoint pjp) {
long startTime = System.currentTimeMillis();
Object result = null;
try {
result = pjp.proceed();
} catch (Throwable e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
logger.info(pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + " spend " + (System.currentTimeMillis() - startTime) + "ms");
return result;
}
}
3. 在需要记录执行时间的方法上加上这个annotation:
@LogExecuteTime
public long myMethod(List<Integer> keys) {
return xxx;
}
运行以后我们就能在log中看到了这个类的这个方法执行了多久。。如果还需要加其它参数,请修改上面的interceptor方法。