Springboot注解实现请求日志

Springboot注解实现请求日志

Springboot注解实现请求日志

1.添加依赖

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

2.创建标记注解

/**
 * 打印方法的详细请求日志
 *
 * @author devcxl
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logging {
}

3. AOP实现

/**
 * @author devcxl
 */
@Slf4j
@Aspect
public class LoggingAspect {

    @Pointcut("@annotation(cn.devcxl.common.annotation.Logging)")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 记录下请求内容
            log.info("[Request] ip:{} -> {} {}", request.getRemoteAddr(), request.getMethod(), request.getRequestURL());
            log.info("[Parameters] {} {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), joinPoint.getArgs());
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        log.info("[Response]: " + ret);
    }

}

如果想要debug某个包下的Controller的话@Pointcut的值可替换为:

execution(* com.example.demo.*.*(..))