Why does Alibaba prohibit engineers from directly using APIs in the logging system (log4j, logback)?

Time:2022-5-27

As a java programmer, I think many people know the importance of logging for a program, especially for web applications. In many cases, logging may be the only way to understand how an application performs.

Therefore, logging is very important in Java Web applications. However, many people think that log output is just a simple thing, so they often ignore issues related to logging.

In the following article, I will introduce this knowledge point that is easy to be ignored but also easy to cause failures.

The Java language is powerful because of its mature ecosystem. Including the logging function, there are many mature open source frameworks that can be used directly.

First, let’s take a look at which frameworks are widely used.

Common log frames

j.u.l

j. U.L is java Util The short name of logging package is the Java Native logging framework introduced by JDK in version 1.4. The Java logging API provides seven logging levels to control output. The seven levels are: severe, warning, info, config, fine, filter, and last.

Log4j

Log4j is an open source project of Apache. By using log4j, we can control that the destinations of log information transmission are console, files, GUI components, even socket server, NT event recorder, UNIX syslog daemon, etc; We can also control the output format of each log;

By defining the level of each log information, we can more carefully control the log generation process. Log4 also has seven log levels: off, fatal, error, warning, info, debug, and trace.

The most interesting thing is that these can be flexibly configured through a configuration file without modifying the application code.

LogBack

Logback is also a mature logging framework. In fact, logback and log4j were created by one person, ceki g ü LC ü.

Logback is currently divided into three modules: logback core, logback classic and logback access.

Logback core is the basic module of the other two modules.

Logback classic is an improved version of log4j. In addition, logback classic fully implements the slf4j API so that you can easily change to other journaling systems such as log4j or j.u.l.

The logback access module is integrated with the servlet container to provide the function of accessing the journal through HTTP.

Log4j2

Log4j was introduced earlier. Here, log4j2 is introduced separately. The reason why log4j2 is not introduced together with log4j is that the author believes that log4j2 is not only an upgraded version of log4j, but has been rewritten from beginning to end. This can be regarded as two completely different frameworks.

We will introduce what problems log4j solves with log4j2 and what advantages log4j2 has over log4j, j.u.l and logback.

Prohibit direct use of log framework API?

The four logging frameworks were introduced earlier. That is to say, when we want to print logs in an application, we can use any of the above four class libraries. For example, if you want to use log4j, you only need to rely on the jar package of log4j, configure the configuration file, and use its API to print logs in your code.

I don’t know how many people have read the Alibaba java development manual. One of the specifications makes “mandatory” requirements:

Why does Alibaba prohibit engineers from directly using APIs in the logging system (log4j, logback)?

picture

The above four common logging frameworks are convenient for Java applications to record logs,Why not use its API directly in the application? What is the slf4j that is highly recommended? What is the so-called facade model?

What is the log facade

Log facade is a typical application of facade mode.

Facade pattern, also known as appearance pattern, its core is that external communication with a subsystem must be carried out through a unified appearance object, making the subsystem easier to use.

Why does Alibaba prohibit engineers from directly using APIs in the logging system (log4j, logback)?

picture

Just like the several logging frameworks described above, each logging framework has its own API. To use the corresponding framework, you must use its corresponding API, which greatly increases the coupling of application code to the logging framework.

To solve this problem, we need to build a communication bridge between the logging framework and applications. For applications, no matter how the underlying logging framework changes, there is no need to have any perception. As long as the facade service is good enough to change another logging framework at will, the application can go online directly without modifying any line of code.

In the field of software development, there is a saying that any problem in the field of computer science can be solved by adding an indirect middle layer. The facade model is a typical practice of this sentence.

Why log facade is required

An important reason mentioned earlier is to shield the specific implementation of the underlying logging framework in the application. In this way, even if you want to change the logging framework of the code one day, you only need to modify the jar package and change the configuration file related to the log output at most. This is to decouple the application from the logging framework.

Some people may ask, if I change the logging framework, the application doesn’t need to be changed. Doesn’t the logging facade still need to be changed?

To answer this question, let’s first give an example, and then crumple the facade pattern and explain it again.

The log facade is like a waiter in a restaurant, while the log frame is like a cook in the kitchen. For the customer app, when I order at the restaurant, I just need to tell the waiter I want a plate of scrambled eggs with tomatoes. I don’t care about everything in the kitchen. Because the chef changed from chef a who called this dish “scrambled eggs with tomatoes” to chef B who called this dish “scrambled eggs with tomatoes”. However, the customer doesn’t need to care. He just gives the order of “scrambled eggs with tomatoes” to the waiter, who then translates it to the chef.

Therefore, for a waiter who knows the “various names of tomato scrambled eggs”, no matter how the cook changes, he can accurately help users place orders.

Similarly, for a comprehensive and perfect log facade, it should be naturally compatible with a variety of log frameworks. Therefore, the log facade hardly needs to be changed for the replacement of the underlying framework.

The above isAn important benefit of the log facade — decoupling

Common log facade

After introducing the concept and benefits of the log facade, let’s take a look at what good log facade implementations are available in the Java ecosystem.

SLF4J

The java simple logging facade for Java (slf4j for short) is a set of interface programs that wrap the logging framework and are implemented in appearance mode. You can decide which logging framework to use during software deployment. Currently, Java logging API, log4j, logback and other frameworks are mainly supported. Issued under MIT authorization.

The author of slf4j is ceki g ü LC ü, the author of log4j and logback. He claims that slf4j is more efficient than log4j, and simpler and more stable than Apache common logging (JCL).

Actually,In fact, slf4j is just a facade service. It is not a real logging framework. The implementation of real log output depends on log4j, logback and other logging frameworks.

Since slf4j is commonly used, we will use more space here to briefly analyze slf4j and compare it with log4j. Compared with the API of log4j, slf4j has the following advantages:

  • Log4j provides six record levels: trace, debug, info, warning, error and fatal. However, slf4j believes that there is no substantial difference between error and fatal, so it removes the fatal level and leaves only the other five.
  • Most people write a logger in the program Error (exception). In fact, log4j will toString the exception at this time. The real writing method should be logger (message.exception); Slf4j will not make the programmer make this mistake.
  • Log4j indirectly encourages programmers to use the method of adding strings (this method has performance problems), but slf4j will not have this problem. You can use logger Error (“{} is+serviceid”, serviceid);
  • Using slf4j, you can easily use the jars of various collective implementations it provides. (similar to commons logger)
  • The Commons – logger and log4j merge are very convenient. Slf4j also provides a swing tool to help you complete this merge.
  • Slf4j only supports MDC, not NDC.
  • It provides the function of string content replacement, which is more efficient. The description is as follows:
//In the traditional string generation method, if there is no debug level information to be recorded, it will waste time on generating unnecessary information Debug ("there are now" + count + "user accounts:" + useraccountlist)// To avoid the above problems, we can first check whether the debug information recording function is enabled, but the coding of the program will be complex if (logger.isdebugnenabled()) {logger.debug ("there are now" + count + "user accounts:" + useraccountlist);}// If the debug level is not enabled, unnecessary strings will not be generated, and the concise logger of the program code can be maintained Debug ("there are now {} user accounts: {}", count, useraccountlist);

commons-logging

Apache common logging is a Java based logging utility and a programming model for logging and other toolkits. It provides API, logging implementation and wrapper implementation through other tools.

The functions of Commons logging and slf4j are similar. They are mainly used for logging facade. Provide more friendly API tools.

summary

In the Java ecosystem, there are many mature solutions around logging. There are two main types of tools for log output.

One is the log framework, which is mainly used to output logs, such as which file to output to and how the log format is. The other is the log facade, which is mainly a set of general APIs used to shield the differences between various log frameworks.

Therefore, for Java engineers, regarding the use of logging tools,The best practice is to use a combination such as log4j + slf4j in the application for log output

The biggest advantage of this is that the development of the business layer does not need to care about the implementation and details of the underlying logging framework, nor does it need to consider the cost of replacing the framework in the future. This is also the benefit of facade mode.

To sum up, please do not use any logging framework APIs such as log4j in your Java code. Instead, you should directly use the logging interface slf4j.

Recommended Today

aggregate

aggregate 1: Set concept Object, which implements common operations on objects, similar to array functions 2: Differences between sets and arrays: The length of array is fixed, and the length of set query is not fixed Arrays can store basic and reference types, while collections can only store reference types Location: java Util* Collection system […]