定義註解類
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
日誌切面實現(AOP實現)
- 定義切面類-註解@Aspect
- 定義切點-@pointcut(表明需要通過什麼方式進行切 @execution() ||@annotation等 )
- 切面通知-前置通知、後置通知、環繞通知(@After @Before @Around @AfterReturing @AfterThrowing)
- 連接點-JoinPoint 以及ProceedingJoinPoint(@Around 環繞通知需要通過該類來處理)類,記錄了,切點方法的入參及類信息
@Component
@Aspect
public class LogAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(com.common.Log)")
private void log(){}
@Around("log()")
public Object handler(ProceedingJoinPoint point) throws Throwable{
Object object = new Object();
StopWatch stopWatch = new StopWatch("logPrintStopWatch");
String errorMsg = null;
try {
LOGGER.info("log print start");
stopWatch.start();
try{
object = point.proceed();
}catch (Throwable e){
errorMsg = e.getMessage();
stopWatch.stop();
throw e;
}
stopWatch.stop();
return object;
}finally {
Object[] args = point.getArgs();
String clazz = point.getTarget().getClass().getName();
String method = point.getSignature().getName();
try{
// 記錄日誌信息
LOGGER.info("記錄日誌-參數:{},類名-{},方法-{}",args,clazz,method);
}catch (Exception e){
LOGGER.error("插入記錄失敗-{}",e.getMessage());
}
LOGGER.info("log print end");
}
}
}
該切面日誌通過在方法裏註解Log,可以實現日誌的統一輸出(也可以通過切某個目錄下的類方法通過@execution()定義)