这篇文章主要介绍了springboot如何使用AOP做访问请求日,志文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
springboot中使用AOP做访问请求日志:这次引入springboot的AOP和日志
1, pom.xml引入:
& lt; !——springBoot的aop,已经集成了spring aop和AspectJ——比; & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-aop & lt;/dependency> & lt; !——https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-logging——比; & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-logging & lt;/dependency>
2,切面类配置:
@ component @Aspect 公开课LogAspect { 私有静态最终日志记录器=LoggerFactory.getLogger (LogAspect.class);//切入点表达式,com.springboot.controller自己控制器包的路径 @Pointcut(“执行(公共* com.springboot.controller . . * . * (. .)”) 公共空间切入点(){ } @Before(“切入点()”) 公共空beforeMethod(连接点的连接点){ ServletRequestAttributes ServletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest请求=servletRequestAttributes.getRequest ();//获取需要打印的参数信息 字符串requestURI=request.getRequestURI (); 字符串方法=request.getMethod (); 字符串remoteAddr=request.getRemoteAddr ();//这里使用的是阿里的fastjson 字符串jsonString=JSON.toJSONString (joinPoint.getArgs ());//打印信息 logger.info(“- - - - - - - - - - - - - - - - - - - - - - - -请求信息- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -”); logger.info(“请求时间:{}”,新SimpleDateFormat (“yyyy-MM-dd HH: mm: ss”)。新日期格式(())); logger.info (“remoteAddr: {}”, remoteAddr); logger.info (“requestURI: {}”, requestURI); logger.info(“控制器:{}”,joinPoint.getTarget () .getClass ()); logger.info(“方法类型:{}”方法); logger.info(“点播帕拉斯:{}”,jsonString); logger.info(“- - - - - - - - - - - - - - - - - - - - - - - -请求信息- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -”); } }
效果:
com.springboot.common.aop.LogAspect: - - - - - - - - - - - - - - - - - - - - - - - -请求信息- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - com.springboot.common.aop.LogAspect:请求时间:2020-01-02 22:38:40 com.springboot.common.aop.LogAspect: remoteAddr: 0:0:0:0:0:0:0:1 com.springboot.common.aop.LogAspect: requestURI:/user/10001 com.springboot.controller.UserController com.springboot.common.aop.LogAspect:控制器类 com.springboot.common.aop.LogAspect:方法类型: com.springboot.common.aop.LogAspect:要求帕拉斯:[10001] com.springboot.common.aop.LogAspect: - - - - - - - - - - - - - - - - - - - - - - - -请求信息- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
这里只做访问请求的日志打印,还可以后置通知,打印响应信息,结合环绕通知可以打印程序执行的时间等其他操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。