springBoot记录Http访问日志(简单入门2)

一.记录请求信息
@Aspect
@Component
public class HttpAspect {

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

    /**
     * 这样写是将重复的代码提取出来方便处理
     */
    @Pointcut("execution(public * com.kafei.HelloController.*(..))")
    public void log() {}

    /**
     *
     * @param joinPoint
     * 注意:该方法中的HttpServletRequest为javax.servlet.http.HttpServletRequest;
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("1");
        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("2");
    }

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


}
二.请求地址:http://127.0.0.1:8080/aa?id=100
三.HelloController.java
@RestController
public class HelloController {

    @GetMapping("/aa")
    public String aa(Girl girl) {
        System.out.println("aa");
        return "aa2";
    }

}

四.结果
2018-05-28 11:19:51.976  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 1
2018-05-28 11:19:51.977  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : url=http://127.0.0.1:8080/aa
2018-05-28 11:19:51.978  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : method=GET
2018-05-28 11:19:51.978  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : ip=127.0.0.1
2018-05-28 11:19:51.980  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : class_method=com.kafei.HelloController.aa
2018-05-28 11:19:51.980  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : args=Girl{id=100, age=null}
aa
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 2
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 3
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : response=aa2
五.总结

1.方法执行顺序:@Before>aa()>@After>@AfterReturning

2.logger.info("url={}",request.getRequestURL());,这里{}理解为变量,request.getRequestURL()理解为该变量的值

你可能感兴趣的:(aop)