Use AOP section to print the operation of each interface in the project

Posted by markmh84 on Sat, 18 Dec 2021 02:11:26 +0100

1. Foreword

AOP aspect technology, you should know, is one of the main functions of the Spring framework.

AOP aspect has a wide range of uses, one of which is to print the operation log and operation time of interface methods.

Log is very important for a project. It is not only helpful for error adjustment, but also an important data source for later big data analysis. Here I will briefly introduce how to print the operation of the back-end interface using AOP in SpringBoot.

2. Section code

The implementation method is very simple. In the SpringBoot project, add an aspect class. The code is as follows:

@Aspect
@Component
@Order(Integer.MIN_VALUE)
public class MyAspect {

    public static final Logger log =
            LoggerFactory.getLogger(MyAspect.class);

    @Around("execution(* cn.zhuifengren.controller..*Controller.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        // Record start time
        long begin = System.currentTimeMillis();

        log.info("Class information:{}", joinPoint.getTarget().getClass());
        log.info("Method name:{}", joinPoint.getSignature().getName());

        // Get request object
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest req = sra.getRequest();
        log.info("Request address: {}",req.getRequestURI());
        log.info("claim device: {}", req.getHeader("user-agent"));

        // Get parameters
        Object[] args = joinPoint.getArgs();
        if (args!=null && args.length>0){
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse)
                    continue;
                log.info("Parameters:" + ( args[i]==null? "": JsonUtils.objectToJson(args[i])));
            }
        }

        // Execute target service
        Object result = joinPoint.proceed();
        log.info("Response:" + JsonUtils.objectToJson(result));

        // Record end time
        long end = System.currentTimeMillis();
        long time = end - begin;

        log.info("Execution time:{} millisecond", time);

        return result;
    }

}

3. Code description

1) The @ Aspect and @ Component annotations are required for the Aspect class to identify that it is an Aspect class.

2) The @ Order(Integer.MIN_VALUE) annotation is used to set the execution order of the slice. The smaller the value, the earlier the slice will be executed.

3)@Around("execution(* cn.zhuifengren.controller...Controller.(...))")

As we all know, there are five notification methods in AOP aspect, including notification before method execution, notification after normal method execution, surround notification, method execution exception notification and final notification.

The @ Around here is the surround notification, that is, it will be notified before and after the method is executed.

execution(* cn.zhuifengren.controller... Controller. (...)) is a faceted expression used to specify which methods will be notified.

The first * represents the method return type * represents all types;

The package name represents the package of the class monitored by aop;

... represents all class methods under the package and its sub packages;

*Controller represents the class name and all classes ending with controller. If all classes are included, write * directly;

** in (...) represents the method name in the class, (...) represents any parameter in the method.

4) Proceedingjoinpoint. This object is the parameter of the facet method, from which you can get the request parameter of the method, and it is also used to execute the method to get the response value.

5)joinPoint.getArgs() gets the parameters.

6)Object result = joinPoint.proceed(), execute the method and get the return value

4. Log effect

Topics: Java Spring Spring Boot AOP