天天看點

SpringBoot使用AOP技術日志列印接口請求資訊

使用aop技術@Around環繞增強的方式簡單實作接口請求相關資訊日志列印功能

相關注解說明:

@Aspect:把目前類辨別為一個切面供容器讀取。

@Pointcut:Pointcut是植入Advice的觸發條件。每個Pointcut的定義包括2部分,一是表達式,二是方法簽名。方法簽名必須是 public及void型。可以将Pointcut中的方法看作是一個被Advice引用的助記符,因為表達式不直覺,是以我們可以通過方法簽名的方式為此表達式命名。是以Pointcut中的方法隻需要方法簽名,而不需要在方法體内編寫實際代碼。

@Around:環繞增強通知。

示例:

1、切面代碼:

@Slf4j
@Aspect
@Component
public class ControllerAOP {

    // 定義切點Pointcut
    @Pointcut("within(com.cai.CJTEST.controller.*)")
    public void excludeService() {
    }

    @Around("excludeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        try {
            log.info("start invoking interface: [{}] params==> {}",
                    pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName(),
                    JSON.toJSONString(args, SerializerFeature.IgnoreNonFieldGetter));
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
        // result的值是被攔截方法的傳回值
        return pjp.proceed();
    }
}
           

2、測試接口:

@GetMapping(path = "/aopTest")
public String aopTest(@RequestParam String param) {
    log.info("start executing interface...");
    return param;
}
           

3、請求接口

SpringBoot使用AOP技術日志列印接口請求資訊

日志列印:

2019-08-21 15:39:07.609 [INFO] [http-nio-8080-exec-1] [com.cai.CJTEST.config.ControllerAOP] 31 - start invoking interface: [com.cai.CJTEST.controller.TestController.aopTest] params==> ["aoppppp"]
2019-08-21 15:39:07.614 [INFO] [http-nio-8080-exec-1] [com.cai.CJTEST.controller.TestController] 148 - start executing interface...
           

注意:Spring AOP的環繞通知會影響到AfterThrowing通知的運作,不要同時使用。