AOP 统一打印请求日志

425 阅读1分钟

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

切面定义

@Slf4j
@Aspect
@Component
public class WebLogAspect {

    @Autowired
    private ObjectMapper mapper;

    @Pointcut("execution(public * com.controller..*.*(..))")
    public void webLog() { }

    /*前置通知,打印请求参数*/
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        log.debug("Request Begin ... ");
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.debug("URL: [{}]", request.getRequestURL().toString());
        log.debug("HTTP Method: [{}]", request.getMethod());
        log.debug("Class Method: [{}].[{}]",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        String requestArgs = mapper.writeValueAsString(joinPoint.getArgs());
        log.debug("Request Args: [{}]", requestArgs);
    }

    /*后置通知,告知请求完成*/
    @After("webLog()")
    public void doAfter() throws Throwable {
        log.debug("Request Done ... ");
    }

    /*环绕通知,计算请求消耗时间*/
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StopWatch sw = StopWatch.createStarted();
        Object result = proceedingJoinPoint.proceed();
        sw.stop();
        log.debug("Request Time {} ms", sw.getTime(TimeUnit.MILLISECONDS));
        return result;
    }
}