本文是SpringBoot通过AOP实现系统日志记录(二)-Service层日志监控,若要实现Controller层监控,请点击传送门:
SpringBoot通过AOP实现系统日志记录(一)-Controller层日志监控(包括日志表设计)
由于公司业务上的需求,现在需要对整个系统做日志性能监控,方便开发人员快速定位系统瓶颈并方便开发人员去解决问题,相关代码如下:
1、引入依赖
<!-- 引入aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、ServiceMonitor监控注解
/**
* @Description: Service监控注解
* @Author: zhangzhixiang
* @CreateDate: 2018/12/09 12:34:56
* @Version 1.0
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceMonitor {
String value() default "";
}
3、Service层代码
/**
* @Description:批量上传公共接口
* @Author:zhangzhixiang
* @CreateDate:2018/08/31 16:39:54
* @Version:1.0
*/
@Service
public class ExcelParseServiceImpl implements ExcelParseService {
private static final Logger logger = LoggerFactory.getLogger(ExcelParseServiceImpl.class);
@Override
@ServiceMonitor
public ExcelParseResultBO excleParse(String fileName, String code, String model) {
//此处省略逻辑代码
}
}
4、ServiceMonitor日志监控拦截器
/**
* @Description:日志监控拦截器
* @Author:zhangzhixiang
* @CreateDate:2018/12/09 12:34:56
* @Version:1.0
*/
@Aspect
@Component
public class ServiceLogAspect {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
private final Logger logger = LoggerFactory.getLogger(this.getClass);
//1、配置匹配ServiceMonitor注解表达式
@Pointcut("@annotation(com.cy.ops.api.common.annotation.ServiceMonitor)")
public void serviceLog() {}
@Around(value = "serviceLog()")
public Object doArount(ProceedingJoinPoint joinPoint) throws Throwable {
//2、记录执行时间
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed(joinPoint.getArgs());
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//3、记录方法名
String methodName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";
logger.info("**********Method:{}, Start:{}, End:{}, Total:{}ms**********",methodName, dateFormat.format(startTime), dateFormat.format(endTime), totalTime);
return result;
}
}
通过以上代码,我们就能愉快的监控这个service方法消耗了多少的时间了,如果还想打印更多的参数,读者可以自行在ServiceLogAspect中进行扩展。
全篇文章完全纯手打,如果觉得对您有帮助,记得加关注给好评哟~~