Log processing:

This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Functional requirements

Log processing needs to record the following:

  1. The requested URL
  2. The visitor IP
  3. Method called
  4. Parameter passed in
  5. Content returned

The above content requires output in the console and log.

When learning this part of the knowledge, really feel harvested a lot, before Spring learning AOP is just a preliminary understanding, now have some in-depth understanding. A good memory is better than a bad writing!

The logging part is mainly the use of AOP, which is integrated into the project by way of aspect, thus reducing the coupling degree between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.

Saying: Aop allows new functionality to be added without changing existing code

What to know:

  • Crosscutting concerns: methods or functions that span multiple modules of an application. That is, the ones that have nothing to do with our business logic, but that we need to focus on, are the crosscutting concerns. Such as logging, security, caching, transactions, etc….
  • ASPECT: A particular object whose crosscutting concerns are modularized. That is, it is a class.
  • Advice: What the aspect must do. That is, it is a method in a class.
  • PointCut: The definition of the “place” that an aspect advises execution.
  • JointPoint: An execution point that matches a pointcut.

There are several other ways to help with Advice, and I’ve listed some of them here:

  1. The doBefore method (executed Before the method) requires the annotation @before implementation
  2. The After method (executed After the method) requires the annotation @after implementation
  3. The doAfterReturning method requires annotating the @AfterRETURNING implementation

See the implementation section below.

Important: Import dependencies

 <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.9.4</version>
 </dependency>
 ​
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
     <scope>test</scope>
 </dependency>
Copy the code

Note: After importing the package, refresh Maven. If you can’t find the package when running, try restarting Maven. There are many solutions online (and tried).

There’s no solution here, just a reminder.

Implementation process:

Create a class (LogAspect), define the class as an Aspect (@Aspect) and add it to the container (@Component).

First create a pointcut, and the following Advice is based on the pointcut:

 @Pointcut("execution(* com.blog.Controller.. *. * (..) )"
 public void log(a){}
Copy the code

The whole expression can be divided into five parts

  1. Execution () : expression body.
  2. The first one*Number: indicates the return type,*The number indicates all types.
  3. Package name: the name of the package to intercept, followed by two periods representing the current package, all subpackages of the current package, com.blog.Controller package, and all class methods under the descendant package.
  4. The second*Number: indicates the class name,*The number represents all classes.
  5. * (..)The third asterisk represents the name of the method, the asterisk represents all methods, the following parentheses represent the parameters of the method, and the two periods represent any parameters

After the pointcut is defined, handle pre – and post-advice:

 @Before("log()")
 public void doBefore(JoinPoint joinPoint){
     System.out.println("Process streams before entering controller -------------");
 }
 @After("log()")
 public void doAfter(a){
     System.out.println("Process streams after entering controller -------------");
 }
 // Cut into the content after the pointcut return content (which can be used to do some processing on the returned value)
 @AfterReturning(returning = "result",pointcut="log()")
 public void doAfterReturning(Object result){
     logger.info("Return ------ {}",result );
 }
Copy the code

From the above brief introduction, we can see that if we need to know the requirements within the requirements, our focus should be on the pre-notification to get the information about the front-end operations before the stream is processed.

The core code is as follows:

 // Obtain the information in the request from the context
 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 ​
 HttpServletRequest request = attributes.getRequest();
 // Get the object that encapsulates the name of the object, where you can get the name of the target method, the Class of the Class, etc. (reflection)
 String classMethod = joinPoint.getSignature().getDeclaringTypeName()+","+joinPoint.getSignature().getName();
 // 1. Obtain the URL
 String url = request.getRequestURL().toString();
 //2. Obtain the IP address
 String addr = request.getRemoteAddr();
 ​
 /* Create a RequestData class to hold the information */
 RequestData requestData = new RequestData(
     url, addr, classMethod, joinPoint.getArgs()
 );
 // Print it in the console
 logger.info("RequestData------{}",requestData);
Copy the code

The class created is an inner class (RequestData) that simply encapsulates the information that needs to be printed.

Experimental results:

Process the stream ------------- before entering controller2021- 08 -15 15:19:43.923  INFO 9644 --- [nio-8080-exec-1] com.blog.AspectAop.LogAspect             : RequestData------RequestData{url='http://localhost:8080/', ipAddr='0:0:0:0:0:0:0:1', classMethod='com.blog.Controller.IndexController,index', args=[]}
 2021- 08 -15 15:19:43.932  INFO 9644 --- [nio-8080-exec-1] com. Blog. AspectAop. LogAspect: Return -- -- -- -- -- - the index after entering the controller processing flow -- -- -- -- -- -- -- -- -- -- -- -- --Copy the code

The github address of the project

References:

God said Spring

Expression parameter

The end:

If you see here or just to help you, I hope you can point to follow or recommend, thank you;

If there are any errors, please point them out in the comments and the author sees them will be corrected.