How does springboot use AOP to log access requests


This article mainly introduces how springboot uses AOP to do access request log. The article introduces in detail through the example code, which has certain reference learning value for everyone’s study or work, and friends in need can refer to it

In springboot, AOP is used to log access requests: this time, the AOP and log of springboot are introduced

1、 pom.xml introduce:

<! -- the AOP of springboot has integrated spring AOP and AspectJ -- >

    <!-- -->

2. Section class configuration:

public class LogAspect {

  private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
  //Pointcut expressions, com.springboot.controller Path of your own controller package
  @Pointcut("execution(public * com.springboot.controller..*.*(..))")
  public void pointCut(){


  public void beforeMethod(JoinPoint joinPoint){
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

    HttpServletRequest request = servletRequestAttributes.getRequest();

      //Get the parameter information to be printed
    String requestURI = request.getRequestURI();
    String method = request.getMethod();
    String remoteAddr = request.getRemoteAddr();
     //Ali's fastjson is used here
    String jsonString = JSON.toJSONString(joinPoint.getArgs());

      //Print information ("--- request information --------"); ("request time: {}", new simpledateformat ("yyyy MM DD HH: mm: SS"). Format (New date()));"remoteAddr: {} ",remoteAddr);"requestURI : {}",requestURI);"Controller : {}", joinPoint.getTarget().getClass());"method type: {}" ,method);"req paras: {}",jsonString); ("--- request information -------- ---";


com.springboot.common . aop.LogAspect    : --- request information----------------------------------
 com.springboot.common . aop.LogAspect    : request time: 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.common.aop.LogAspect   : Controller : class com.springboot.controller.UserController
 com.springboot.common.aop.LogAspect   : method type: GET
 com.springboot.common.aop.LogAspect   : req paras: [10001]
 com.springboot.common . aop.LogAspect    : --- request information---------------------------------

Here, we only print the log of access request. We can also print the post notification, print the response information, and print the execution time of the program in combination with the surrounding notification.

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.