Spring Boot uses Aop for log global interception

Keywords: Spring Java Programming SpringBoot

Spring Boot uses Aop for log global interception


The previous chapters we learned Spring Boot Log Log Use Tutorial and Spring Boot exception handling and global exception handling In this chapter, we combine Aop face-to-face programming to achieve global exception interception and log.

In Spring Boot, Aop and Ioc are the souls of Spring, and their functions are very powerful.

Source Download for this project

1 New Spring Boot Project

1) File > New > Project, select Spring Initializr as shown below and click Next to proceed

2) Fill in GroupId (package name), Artifact (project name).Click Next
groupId=com.fishpro
artifactId=aoplog

3) Choose to rely on Spring Web Starter for front hooking.

4) Project name set to spring-boot-study-aoplog

Introducing aop dependency in 2 Pom

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3Write processing code

3.1 Procedure Principle and Process

Using the @Aspect annotation to implement aop in the SpringBoot application is very simple.The main implementation of this sample code is

This code adds four new files, the file list is as follows, the slash is in front of the package name, need to create a new

  • Anntation/Log.java Custom Log Interception Annotation
  • aspect/LogAspect.java Custom Log Interception Annotation Trigger Conditions, Enhancement of Surround (Execution Logic Before and After Request)
  • aspect/WebLogAspect.java Web-based log interception defines Web pre-request, post-request, and request lifecycle actions
  • Controller class for controller/IndexController.java control layer, easy to test, fixed/log

New notes used in this example include

  • @Aspect Face Oriented Programming Annotation, commonly used on classes
  • @Pointcut Pointcut is the trigger condition for implanting Advice.Each Pointcut is defined in two parts: an expression and a method signature.Method signature must be public and void.You can think of a method in Pointcut as a mnemonic referenced by Advice because the expression is not intuitive, so we can name it by signing the method.So the method in Pointcut only needs a method signature, not actual code inside the method body
  • @Around: Enhanced surround, equivalent to MethodInterceptor
  • @AfterReturning: Post-enhancement, equivalent to AfterReturningAdvice, executed when the method exits normally
  • @Before: Identify a pre-enhancement method, equivalent to BeforeAdvice's capabilities, and similar capabilities
  • @AfterThrowing: Enhancement of exception throw, equivalent to ThrowsAdvice
  • @After: final enhancements, executed regardless of exception throw or normal exit

Process description

As shown in the diagram, when a user accesses IndexController's/log route, information with the @log annotation method is intercepted by WebLogAspect, which handles both pre-request and post-request information and stores it in the log according to the definition in WebLogAspect.

3.2 Custom Log Comment@log

This article does not intend to elaborate on what custom annotations are, how they are used, and what you can know is that

  • Annotations are a form of metadata.That is, annotations are a data type that belongs to java and are similar to classes, interfaces, arrays, enumerations
  • Annotations are used to modify classes, methods, variables, parameters, packages.
  • Annotations do not have a direct impact on the code being modified.

Define the comment @Log, Log.java under the anotation package

/**
 * Use @interface to define a comment Here is the log
 * For log aop programming
 * */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String value() default "";
}

How to use it, I do not use the @Log annotation in the IndexController method

3.3 Define IndexController for Testing

@Controller
public class IndexController {

    @Log("Log notes, collaboration WebAspect Record requests before, after, and during the process")
    @RequestMapping("/log")
    @ResponseBody
    public String log(String name){
        return "log";
    }
}

3.4 Define the aop class LogAspect and WebLogAspect

@Aspect
@Component
public class LogAspect {
    private static final Logger logger=LoggerFactory.getLogger(LogAspect.class);

    /**
     * Here you specify the com.fishpro.aoplog.annotation.Log annotation using @annotation
     * */
    @Pointcut("@annotation(com.fishpro.aoplog.annotation.Log)")
    public void logPointCut(){

    }

    public  Object around(ProceedingJoinPoint point) throws Throwable{
        long beginTime = System.currentTimeMillis();
        // Execution Method
        Object result = point.proceed();
        // Execution time (milliseconds)
        long time = System.currentTimeMillis() - beginTime;
        //Save log asynchronously Here is the text log

        return result;
    }

    void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException{

    }
}
@Aspect
@Component
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    /**
     * Specify comments under the controller package
     * */
    @Pointcut("execution( * com.fishpro.aoplog.controller.*.*(..))")//Two... represent all subdirectories, two in the last bracket... represent all parameters
    public void logPointCut() {

    }

    /**
     * Specifies that the current execution method is executed before logPointCut
     * */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        // Receive request, record request content
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // Record the request
        logger.info("Request Address : " + request.getRequestURL().toString());
        logger.info("HTTP METHOD : " + request.getMethod());
        // Get the real ip address
        //logger.info("IP : " + IPAddressUtil.getClientIpAddress(request));
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        logger.info("parameter : " + Arrays.toString(joinPoint.getArgs()));
        //loggger.info("Parameters:"+ joinPoint.getArgs()));
    }
    /**
     * Specify to return after method
     * */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")// The value of returning is the same as the parameter name of doAfterReturning
    public void doAfterReturning(Object ret) throws Throwable {
        // After processing the request, return the content (when the return value is too complex, print the address of the physical storage space)
        logger.info("Return value : " + ret);
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();// ob is the return value of the method
        logger.info("time consuming : " + (System.currentTimeMillis() - startTime));
        return ob;
    }
}

3.5 Test

In browser input, note that the port has been changed to 8085 in application.yml

http://localhost:8085/log?name=fishpro
Output in console

2019-07-13 17:12:15.388  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : Request Address : http://localhost:8085/log
2019-07-13 17:12:15.388  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : HTTP METHOD : GET
2019-07-13 17:12:15.389  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : CLASS_METHOD : com.fishpro.aoplog.controller.IndexController.log
2019-07-13 17:12:15.389  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : parameter : [fishpro]
2019-07-13 17:12:17.219  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : time consuming : 4934
2019-07-13 17:12:17.997  INFO 10055 --- [nio-8085-exec-1] com.fishpro.aoplog.aspect.WebLogAspect   : Return value : log

Source Download for this project

Associated reading:

Spring Boot Log Log Use Tutorial

Spring Boot Global Exception Handling

Consult microsignal fishpro or QQ number 502086 if you have questions

20 original articles published, 0 praised, 134 visits
Private letter follow

Posted by hessodreamy on Sat, 14 Mar 2020 19:57:04 -0700