Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement AOP Log processing by SpringBoot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces SpringBoot how to achieve AOP log processing, the article is very detailed, has a certain reference value, interested friends must read it!

Log processing:

Demand analysis

Log processing needs to be recorded as follows:

Requested URL

Visitor IP

Called method

Parameters passed in

What is returned

The above is required to be output in the console and log.

In learning this part of the knowledge, I really feel that I have gained a lot. Before, the aop that Spring learned was only a preliminary understanding, but now I have some in-depth understanding. A good memory is not as good as a bad pen!

In the log processing part, it is mainly the use of aop, which is integrated into the project through the aspect way, so that the coupling between the various parts of the business logic is reduced, the reusability of the program is improved, and the efficiency of development is improved.

Voice: Aop adds new functions without changing the original code

What you need to know:

Crosscutting concern: a method or function that spans multiple modules of an application. That is, what has nothing to do with our business logic, but what we need to focus on, is crosscutting concerns. Such as logs, security, caching, transactions and so on.

ASPECT: special objects where crosscutting concerns are modularized. That is, it is a class.

Advice: the work that must be done in a section. That is, it is a method in the class.

Pointcut (PointCut): the definition of the "place" where the facet notification is executed.

JointPoint: the execution point that matches the pointcut.

Notification (Advice) also has several methods to help with the implementation, here I list the methods of this part of the implementation:

The doBefore method (executed before the method), which requires annotated @ Before implementation

The After method (executed after the method), which requires annotated @ After implementation

DoAfterReturning method, which needs to be annotated with @ AfterReturning implementation

For the specific implementation, see the later part.

Important part: import dependencies

Org.aspectj aspectjweaver 1.9.4 org.springframework.boot spring-boot-starter-aop test

Reminder: after importing the package, refresh the Maven. If you can't find the package while running, restart it. There are many solutions on the Internet (also tried). Finally, the individual just restarts and refreshes the maven and can use it.

There is 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 () {}

The whole expression can be divided into five parts

1. Execution (): expression body.

2. The first * sign: indicates the return type, and the * sign indicates all types.

3. Package name: indicates the name of the package to be intercepted. The next two periods represent the current package and all subpackages of the current package, and the methods of all classes under the com.blog.Controller package and descendant package, respectively.

4. The second * sign: indicates the class name, and the * sign represents all classes.

5. * (..): the third asterisk indicates the method name, the * sign indicates all methods, the parentheses indicate the parameters of the method, and the two periods indicate any parameters.

After defining the pointcut, process the pre-notification and post-notification:

@ Before ("log ()") public void doBefore (JoinPoint joinPoint) {System.out.println ("process stream before entering controller -");} @ After ("log ()") public void doAfter () {System.out.println ("process stream after entering controller -") } / / enter 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);}

Through the above brief introduction, we can know that if we need to know the requirements in the requirements, we should focus on the pre-notification to obtain the information of the front-end operation before the stream processing.

The core code is as follows:

/ / get the information in the request through the context ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = attributes.getRequest (); / / get the object that encapsulates the signature information, in which you can get the target method name, Class and other information of the class (reflection) String classMethod = joinPoint.getSignature (). GetDeclaringTypeName () + "," + joinPoint.getSignature (). GetName (); / / 1. Get URLString url = request.getRequestURL (). ToString (); / / 2. Get the ip address String addr = request.getRemoteAddr (); / * create a class RequestData to hold the relevant information * / RequestData requestData = new RequestData (url, addr, classMethod, joinPoint.getArgs ()); / / print out logger.info ("RequestData- {}", requestData) on the console

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

Experimental results:

Process the stream before entering the controller

2021-08-15 15 nio-8080-exec-1 1918 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 com.blog.AspectAop.LogAspect 1914 43.932 INFO 9644-[nio-8080-exec-1] com.blog.AspectAop.LogAspect: Return-index

Process the stream after entering controller-

The above is all the content of the article "how to implement AOP log processing in SpringBoot". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report