ExecuteTime注解
@Target(ElementType.METHOD)//注解用在方法上,用于描述方法
@Retention(RetentionPolicy.RUNTIME)//注解在运行时保留
@Documented//指定javadoc生成API文档时显示该注解信息
public @interface ExecuteTime {
//调用时长阈值,默认为0,单位为毫秒,运行时长超过threshold毫秒时打印运行时长日志
int threshold() default 0;
String msg() default "";
String postfix() default "接口---执行时长:{}毫秒";
//日志级别
LogLevel logLevel() default LogLevel.info;
}
InvokeTimeAdvice
@Aspect
public class InvokeTimeAdvice {
@Pointcut("execution(public * com.htjc..*.*(..))&&@annotation(executeTime)")
public void pointCut(ExecuteTime executeTime) {
}
;
@Around("pointCut(executeTime)")
public Object logInvokeTime(ProceedingJoinPoint joinPoint, ExecuteTime executeTime) throws Throwable {
long start = System.currentTimeMillis();//开始时间
final Logger LOGGER = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
try {
return joinPoint.proceed();
} finally {
long end = System.currentTimeMillis();//结束时间
long duration = end - start;
if (duration >= executeTime.threshold()) {
String msg = executeTime.msg();
if (msg == null || msg.trim().length() == 0) {
String methodName = joinPoint.getSignature().getName();//方法名
LogUtils.log(LOGGER, executeTime.logLevel(), "方法[{}]执行时长:{}毫秒", methodName, duration);
}
} else {
LogUtils.log(LOGGER, executeTime.logLevel(), executeTime.msg() + executeTime.postfix(), duration);
}
}
}
}
advice bean注入applicationContext.xml
<!--切面 start-->
<!--记录方法执行时长-->
<bean id="invokeTimeAdvice" class="com.common.aspect.InvokeTimeAdvice"></bean>
<!--切面 end-->