When used in some software, such as Taobao or Book, it can construct and analyze user behavior data by recording user behavior, while also better optimizing product design and improving user experience. For example, in an order system, it is necessary to determine the behavior of tracking users, such as:
- Login/Login
- Browse products
- Purchase more
- Search product keywords
- Place an order
The above behavior requires the use of the log system to store or record data. Java has several logging solutions, which briefly introduces several implementation solutions and points to pay attention to.
Issues needing attention to log addition
Depending on the business, it is necessary to use matching appropriate logging schemes. There are also several issues to be paid attention to:
- It cannot affect the original business logic.
- An error cannot be reported. Even if an error is reported, it cannot affect the original business code.
- For time-consuming log code, use an asynchronous method
- Low intrusiveness, try to change the original code as little as possible
Spring AOP
Spring AOP realizes the ability to dynamically add functions without modifying the original code through aspect programming. This method has the following benefits:
- Low invasiveness
- Strong reusability
This article uses annotation-based AOP, and first defines a sectional annotation AopTest:
/** * Sectional annotation */ @Target({, }) @Retention() public @interface AopTest { }
Create notification again @Around:
@Around("@annotation()") public Object annotationTest(ProceedingJoinPoint joinPoint) throws Throwable { ("Before execution"); Object result = (); // Execute the target method Object[] args = (); ("After execution"); return result; }
Usually it will be inAfter execution
Just add logs. If you want to add logs to that method or interface, you only need to add annotations to the method, such as adding annotations to the interface:
@GetMapping @AopTest public String first(String param) { ("Execute the first method"); return "result " + param; }
After requesting the interface, the following output is:
Before execution
Execute the first method
After execution
However, there is a problem with the section. If the execution section error is reported, the method cannot be executed. Therefore, it is necessary to catch exceptions to ensure the normal execution of the business code. Revise the above notification:
@Around("@annotation()") public Object annotationTest(ProceedingJoinPoint joinPoint) throws Throwable {("Before execution"); ("Before execution"); Object result = (); // Execute the target method try { Object[] args = (); // Add log ("After execution"); int a = 1/0; } catch (Exception e) { (()); } return result; }
After transformation, even if an error occurs in the section, it will not affect the execution of the business code.
AOP is executed synchronously. If log addition is a time-consuming operation, it will also affect the response speed of the interface. At this time, you can use asynchronous methods, such as message queues.
To sum up, Spring AOP has the following advantages and disadvantages.
advantage:
- Low invasiveness
- Strong reusability
Disadvantages and solutions:
1. Reporting errors in the section may affect the business code
Problem: If exceptions on the section are not handled correctly, they may affect the normal execution of the business code.
Solution:
- Catch exceptions to ensure normal business code execution
- Generally, try catch catches to prevent upward propagation
2. Synchronous execution will affect the interface response speed
Problem: If there is a time-consuming operation in the section, synchronous operation will cause the interface to respond slowly.
Solution:
- Time-consuming operations are executed asynchronously through message queue
- Use @Async to execute the method asynchronously, separate the task from the main thread, and hand it over to other thread pools for execution
Event Listening + Asynchronous
Spring event listening mechanism is aPublish-Subscribe
mode, decouple the release and listening of events. Through this mechanism, the publisher of the event does not need to pay attention to the listening logic, and the listener does not need to rely directly on the publisher.
Spring event listening is composed of three parts:
1. Events
Customize an event and inherit ApplicationEvent:
@Getter @Setter public class DemoEvent extends ApplicationEvent { private String name; public DemoEvent(Object source) { super(source); } }
2. Event monitoring
Listen events based on @EventListener annotation:
@Component @Slf4j public class DemoEventListener { @EventListener public void handleEvent(DemoEvent event){ (()); ("Event Listening"); } }
3. Event release
Use the method to publish events,
@Autowired private ApplicationEventPublisher applicationEventPublisher; @Override public void publish() { // Execute business code ("Perform login,Current time {}",()); DemoEvent event = new DemoEvent(this); ("hello"); (event); ("Complete login,Current time {}",()); ("Execute service"); }
After configuring the release and listening of events, add the release of events in the business code and add log records within the listening method.
Although Spring event listening decouples publishing and listening, it only decouples logical code, both of them are stillSynchronous execution
, and they are all executed on the same thread, so event listening cannot solve the problem of adding log errors and time-consuming.
4. Verify whether the listening method is synchronized
Add a delay in event listening:
@EventListener public void handleEvent(DemoEvent event){ try { (2000); } catch (InterruptedException e) { (); } (()); ("Event Listening"); }
Console output:
Execute login, current time 16:52:30.799
hello
Event listening
Complete login, current time 16:52:33.799
Execute service
The interface has been executed for more than 3 seconds, and the publish method must wait for the listening method to be executed before it can be executed.Event listening is synchronous
。
5. Verify whether the error in the listening method will affect the main process
Add error code to the listening method:
@EventListener public void handleEvent(DemoEvent event){ int a = 1/0; (()); ("Event Listening"); }
Console output:
Execute login, current time 17:10:08.396
: / by zero
The monitoring method has an error, the interface has also been reported, and the business code cannot be executed, explanationThe monitoring method error will affect the event publishing method
。
To solve the problem of errors, use exception capture. The problem of delay needs to be usedasynchronous
Operation,Asynchronous means to enable another thread to execute listening method
,Asynchronous not only solves the problem of delay, but also solves the problem of errors.
Implement asynchronously adding @Async asynchronous annotations to the listening method, and add delays and error codes to the listening method:
Execute login, current time 17:21:50.971
Complete login, current time 17:21:50.974
Execute service
The publish method will neither delay nor affect execution due to listening to errors. Asynchronously solves the time-consuming and error-reporting problems
Message Queue
In massive log scenarios, message queues are a good choice, and they also decouple publishers and subscribers. If subscribers enable manual confirmation, consumers also need to use try catch to capture exception information to ensure that messages can be consumed normally.
Summarize
This article introduces several logging implementation solutions:
-
Spring AOP
:- Advantages: Low invasiveness, strong code repeatability
- Problem and solutions:
- An error may be reported in the section, and the error will affect the normal execution of the business code. The solution is to use try catch to catch the exception.
- Logging will affect the efficiency of business code execution, and you can use message queues to perform log operations asynchronously.
-
Event Listening + Asynchronous
:- Advantages: Decoupling business logic and logging to improve the cohesion of code.
- Disadvantages and solutions:
- There are problems with AOP, event listening, and error reporting and time-consuming will affect the business code. An error can be caught using exceptions, and the delay problem can be solved using asynchronous method. Asynchronous threads also solve the problem of errors affecting business code.
-
Message Queue
:- Advantages: Used in high concurrency diary recording scenarios
- Problem: To increase the complexity and stability of the system, we also need to consider the loss of messages and repeated consumption issues.
This is the end of this article about the summary of the implementation of logging in Java. For more related Java logging content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!