很簡單,
通過AOP實作每個方法通路時候統一進行日志列印和耗時計算,
相關配置:
1、spring配置
在spring配置xml檔案中設定啟用aop
<aop:aspectj-autoproxy proxy-target-class="true" />
2、aop具體業務類(通過注解的方式,使用“環繞通知”)
@Aspect
@Component
public class LoggingAspect {
private static final Log logger = LogFactory.get();
// service層的統計日志/耗時(方法所在的包)
public static final String POINT = "execution (* cn.xx.xx.xxxxx.service.impl.*.*(..))";
/**
* 統計方法執行耗時Around環繞通知
* @param joinPoint
* @return
*/
@Around(POINT)
public Object loggingAround(ProceedingJoinPoint joinPoint) {
long startTime = System.currentTimeMillis();
// 定義傳回對象、得到方法需要的參數
Object resultData = null;
Object[] args = joinPoint.getArgs();
Object apiName = args[0];
try {
// 調用釘釘接口
logger.info("======>請求[xxx]接口開始,參數:{}", args);
resultData = joinPoint.proceed(args);
long endTime = System.currentTimeMillis();
logger.info("======>請求[xxx]接口完成,耗時:{},傳回:{}", (endTime - startTime), resultData);
} catch (Throwable e) {
// 記錄異常資訊
long endTime = System.currentTimeMillis();
logger.error("======>請求[xxx]接口異常!耗時:{}", (endTime - startTime));
}
return resultData;
}
}
配置完成!