1、请求controller入口

@Controller
public class IndexController {
@GetMapping({"/", "/index"})
    public String index() {
        return "index";
    }
}

2、拦截器

@Aspect
@Component
public class RequestInterceptor implements HandlerInterceptor {
/**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut(value = "execution(public * com.example.controller..*.*(..))")
    public void reqOpenAPILog() {
    }
        /**
     * 在切点之前织入
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("reqOpenAPILog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
 	        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求 url
        logger.info("Request URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        logger.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        logger.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        logger.info("Request IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        logger.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));

    /**
     * 在切点之后织入
     *
     * @throws Throwable
     */
    @After("reqOpenAPILog()")
    public void doAfter() throws Throwable {
        // TODO: 2022/6/6 doSth(). 
    }
    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("reqOpenAPILog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        logger.info("========================================== Start ==========================================");
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        logger.info("Response Args  : {}", new Gson().toJson(result));
        // 执行耗时
        logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        logger.info("=========================================== End ===========================================");
        return result;
    }


 }

3、浏览器请求:http://localhost:9091/index
在这里插入图片描述
4、日志控制台输出
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐