System.out.println() has been used for debugging before. But deploying a project in production environment in this way will degrade the performance of the application because of the numerous console outputs. Log4J becomes a powerful tool for balancing the development and deployment of applications.
Using Log4J in a project is not a difficult task. The simple and crude way is to declare a Logger private property in each class A
This is simple, but it brings two problems:
1. Increase system overhead - each class using Log4J adds object attributes.
2. Trouble: Every class using Logger has to declare the above Logger object repeatedly.
It's not hard to find that you can use refactoring to declare a common class Log4jUtils to handle Logger's public operations.
But the problem is not so simple. First of all, to solve a problem, what's the use of A.class in Logger.getLogger(A.class)? Can A.class be blind?
Let's do an experiment. First, simply configure the log4j.properties file.
Create a new test class
View the results:
It is not difficult to know the category to which% c output belongs, usually the full name of the class in which it belongs. But what we're tracking is the LoggerTest class, which returns java.lang.Object, which is misleading.
Modify the code of the LoggerTest class at this point
The results of operation are as follows:
The result is finally there. At this point, I understand the parametric purpose of getLogger(class): tracking the class that generated this log.
Now a new problem arises: how to deal with the parameter problem of getLogger(class) if you want to use a class Log4jUtils to deal with operations such as the declaration of Logger objects?
That is, how to get the type of logger object invoked in Log4jUtils.
The solution to this difficulty can be to use Java Reflection mechanism
Look at the following code:
Class Log4jUtils:
Modify the code for the LoggerTest class:
Operation results:
It's great to see this result. In the future, the project can give up using System.out.println() to print statements.