SpringBoot AOP记录http请求

1、在pom.xml中添加aop依赖

		<!--AOP依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

2、AOP处理请求

@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    //..表示方法里面的任何参数都会拦截.GirlController.*会拦截所有方法
    //这里@Pointcut定义了一个切点,
    @Pointcut("execution(public * com.wang.controller.GirlController.*(..))")
    public void log() {
    }

    @Before("log()")    //方法执行之前,记录http请求
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        logger.info("url={}", request.getRequestURL());

        //method
        logger.info("method={}", request.getMethod());

        //ip
        logger.info("ip={}", request.getRemoteAddr());

        //类方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //参数
        logger.info("args={}", joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        logger.info("222222222222");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}", object.toString());
    }

}

3、结果

2018-10-01 23:09:29.262  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : url=http://localhost:8081/girl/girllist
2018-10-01 23:09:29.264  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : method=GET
2018-10-01 23:09:29.264  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : ip=0:0:0:0:0:0:0:1
2018-10-01 23:09:29.270  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : class_method=com.wang.controller.GirlController.listAllGirl
2018-10-01 23:09:29.274  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : args={}
2018-10-01 23:09:29.387  INFO 45556 --- [io-8081-exec-10] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select girl0_.id as id1_0_, girl0_.age as age2_0_, girl0_.name as name3_0_ from girl girl0_
2018-10-01 23:09:29.688  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : 222222222222
2018-10-01 23:09:29.689  INFO 45556 --- [io-8081-exec-10] com.wang.aspect.HttpAspect               : response=[Girl{id=1, name='赵', age=22}, Girl{id=2, name='钱', age=22}, Girl{id=3, name='A', age=18}, Girl{id=4, name='B', age=19}, Girl{id=5, name='孙', age=22}, Girl{id=6, name='李', age=22}, Girl{id=7, name='李', age=22}]

猜你喜欢

转载自blog.csdn.net/ZHWang102107/article/details/82919783