SpringBoot AOP處理請求日誌處理打印

SpringBoot AOP處理請求日誌處理打印

@Slf4j
@Aspect
@Configuration
public class RequestAopConfig {

    @Autowired
    private HttpServletRequest request;

    private static final ThreadLocal<Long> START_TIME_MILLIS = new ThreadLocal<>();

    @Pointcut("execution(* com.xxx.xxx.xxx..*(..)) " +
            "&&(@annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PutMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.DeleteMapping))")
    public void controllerMethodPointcut() {
    }

    /**
     * 前置通知:在某鏈接點以前執行的通知,但這個通知不能阻止鏈接點以前的執行流程(除非它拋出一個異常)。
     *
     * @param joinPoint 參數
     */
    @Before("controllerMethodPointcut()")
    public void before(JoinPoint joinPoint) {
        START_TIME_MILLIS.set(System.currentTimeMillis());
    }

    /**
     * 後置通知:在某鏈接點正常完成後執行的通知,一般在一個匹配的方法返回的時候執行。
     *
     * @param joinPoint 參數
     */
    @AfterReturning(value = "controllerMethodPointcut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String logTemplate = "--------------- 執行成功 ---------------\n請求開始---Send Request URL: {}, Method: {}, Params: {} \n請求方法---ClassName: {}, [Method]: {}, execution time: {}ms \n請求結束---Send Response Result: {}";
        log.info(logTemplate, request.getRequestURL(), request.getMethod(), JSON.toJSONString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), (System.currentTimeMillis() - START_TIME_MILLIS.get()), JSON.toJSONString(result));
        START_TIME_MILLIS.remove();
    }

    /**
     * 異常通知:在方法拋出異常退出時執行的通知。
     *
     * @param joinPoint 參數
     */
    @AfterThrowing(value = "controllerMethodPointcut()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        String logTemplate = "--------------- 執行失敗 ---------------\n異常請求開始---Send Request URL: {}, Method: {}, Params: {} \n異常請求方法---ClassName: {}, [Method]: {}, execution time: {}ms \n異常請求結束---Exception Message: {}";
        log.error(logTemplate, request.getRequestURL(), request.getMethod(), JSON.toJSONString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), (System.currentTimeMillis() - START_TIME_MILLIS.get()), ex.getMessage());
        START_TIME_MILLIS.remove();
    }

    /**
     * 最終通知。當某鏈接點退出的時候執行的通知(不管是正常返回仍是異常退出)。
     *
     * @param joinPoint
     */
    @After("controllerMethodPointcut()")
    public void after(JoinPoint joinPoint) {
    }
}

趙小胖我的博客java

相關文章
相關標籤/搜索