Spring boot log processing based on AOP

When using spring boot for development, we can get the log information we want through AOP and print it on the console.

1, Import AOP related initiators

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

2, Writing a class for faceted logging

/**
 * This is a class that uses AOP to complete log interception
 */
@Aspect
@Component
public class LogAspect {

    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    //Define facets and monitor all requests to access cn.xsh.blog.controller directory
    @Pointcut("execution(* cn.xsh.blog.controller.*.*(..))")
    public void log(){}

    //Define the method to execute before entering the cut plane
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //Get HttpServletRequest object get related data in the request
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();  //Get request object
        String url=request.getRequestURL().toString();   //Get the requested url
        String ip=request.getRemoteAddr();     //Get the ip address of the request object
        String classMethod= joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
            //Get the method name of the request object request
        Object [] args=joinPoint.getArgs();     //Get request parameters of request object
        RequestLog requestLog=new RequestLog(url,ip,classMethod,args);
        logger.info("Request : {}",requestLog);
    }
    //Define how to complete execution in faceted access
    @After("log()")
    public void doAfter(){
        logger.info("------------doAfter-----------------------");
    }
    //Define the method to get the value returned by the accessed Controller and print it in the log
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturning(Object result){
        logger.info("Result : {}",result);
    }

    //Define internal classes to represent the relevant log information that needs to be obtained before the request
    private class RequestLog{
        private String url;  //Requested url
        private String ip;  //Requester's ip
        private String classMethod;  //Target request method of requester
        private Object[] args;  //Request parameters

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}

Notes related to AOP:

@Aspect: identifies the current class as a facet for the container to read
@Pointcut: pointcut is the trigger for embedding Advice. The definition of each pointcut includes two parts, one is expression, the other is method signature. Method signature must be public and void. The method in pointcut can be regarded as a mnemonic referenced by Advice. Because the expression is not intuitive, we can name it by method signature. Therefore, the method in pointcut only needs method signature, and does not need to write the actual code in the method body.
@Around: surround enhancement, equivalent to MethodInterceptor
@AfterReturning: Post enhancement, equivalent to AfterReturning advice, which is executed when the method exits normally
@Before: identify a pre enhancement method, which is equivalent to the function of BeforeAdvice. Similar functions include
@AfterThrowing: exception throwing enhancement, equivalent to ThrowsAdvice
@After: final enhancement, whether it is to throw an exception or exit normally, it will execute

Published 17 original articles, praised 0, visited 175
Private letter follow

Keywords: Spring

Added by pyro3k on Fri, 21 Feb 2020 09:42:41 +0200