1.在父工程的pom.xml引入相应的依赖包
<!--aop 切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.在config包中创建ServiceLogAspect类
@Aspect
@Component
public class ServiceLogAspect {
public final static Logger log =LoggerFactory.getLogger(ServiceLogAspect.class);
/**
* AOP通知:
* 1.前置通知: 在方法调用之前执行
* **2.后置通知: 在方法正常调用之后执行 (方法报异常,执行不了)
* 3.环绕通知: 在方法调用之前和之后,都分别可以执行的通知
* 4.异常通知:如果在方法调用过程中发生异常,则通知
* **5.最终通知:在方法调用之后执行
*/
@Around("execution(* com.lzx.service.impl..*.*(..))")
public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("===============开始执行{}.{}==============",
joinPoint.getTarget().getClass(),
joinPoint.getSignature().getName());//标明执行某个service的某个方法
//记录时间
long begin = System.currentTimeMillis();
//执行目标
Object result = joinPoint.proceed();
//记录结束时间
long end = System.currentTimeMillis();
//所用时间
long takeTime = end- begin;
if (takeTime > 3000) {
log.error("==========执行结束,耗时:{}毫秒========",takeTime);
} else if (takeTime > 2000 && takeTime <3000){
log.error("==========执行结束,耗时:{}毫秒========",takeTime);
} else {
log.error("==========执行结束,耗时:{}毫秒========",takeTime);
}
return result;
}
}