Using SLF4J and Logback

The good friends Commons Logging and Log4j are introduced earlier. One of them is responsible for the log API, and the other is responsible for implementing the bottom layer of the log. It is very easy to develop when used together.

Some children’s shoes may also have heard of SLF4J and Logback. These two things also look like logs, what are they?

In fact, SLF4J is similar to Commons Logging and is also a log interface, while Logback is similar to Log4j and is a log implementation.

Why with Commons Logging and Log4j, SLF4J and Logback pop up again? This is because Java has a very long history of open source. Not only is OpenJDK itself open source, but almost all of the third-party libraries we use are open source. A particular feature of the rich open source ecosystem is that for the same function, several competing open source libraries can be found.

Because of dissatisfaction with the interface of Commons Logging, some people engaged in SLF4J. Because of dissatisfaction with the performance of Log4j, some people engaged in Logback.

Let’s first take a look at how SLF4J improves the Commons Logging interface. In Commons Logging, we want to print the log, sometimes we have to write:

Spelling strings is a very troublesome thing, so the log interface of SLF4J has been improved as follows:

We can guess by guessing. The log interface of SLF4J passes in a string with placeholders, and the placeholders are automatically replaced with the following variables, so it looks more natural.

How to use SLF4J? Its interface is actually almost identical to Commons Logging:

Compare the interfaces of Commons Logging and SLF4J:

Commons LoggingSLF4J

The difference is that Log becomes Logger, and LogFactory becomes LoggerFactory.

Using SLF4J and Logback is similar to using Commons Logging and Log4j as mentioned earlier. First download SLF4J and Logback respectively , and then put the following jar packages on the classpath:

  • slf4j-api-1.7.x.jar
  • logback-classic-1.2.x.jar
  • logback-core-1.2.x.jar

Then use SLF4J’s Logger and LoggerFactory. Similar to Log4j, we still need a Logback configuration file, logback.xmlput it on the classpath, and configure it as follows:

Run it to get output similar to the following:

Judging from the current trend, more and more open source projects have shifted from Commons Logging plus Log4j to SLF4J plus Logback.


According to the configuration file, observe the log files written by Logback.



SLF4J and Logback can replace Commons Logging and Log4j;

Always use SLF4J’s interface to write logs. Using Logback only requires configuration and no code modification.

Java NullPointerException

Of all the RuntimeExceptionexceptions, Java programmers are probably most familiar with NullPointerException.

NullPointerException is the null pointer exception, commonly known as NPE. This exception is usually thrown by the JVM if an object is null called, its methods are called or its fields are accessed , for example:NullPointerException

The concept of pointers is actually derived from the C language, and there are no pointers in the Java language. The variables we define are actually references, Null Pointer is more precisely Null Reference, but the difference between the two is not much.

Handling NullPointerException

If encountered NullPointerException, how should we deal with it? First of all, it must be clear that it NullPointerExceptionis a code logic error. When encountered NullPointerException, follow the principle of early exposure and early repair. It is strictly prohibited to use catchto hide such coding errors:

Good coding practices can greatly reduce NullPointerExceptionthe occurrence of, for example:

Member variables are initialized when they are defined:

A lot can be avoided by using an empty string ""instead of the default , and when writing business logic, it is much safer to use an empty string for unfilled .nullNullPointerException""null

Returns an empty string "", an empty array instead of null:

This saves the caller from having to check whether the result is null.

If the caller must make nulljudgments, such as returning to nullindicate that the file does not exist, then consider returning Optional<T>:

In this way, the caller must pass the Optional.isPresent()judgment whether there is a result.

Locating NullPointerException

If generated NullPointerException, for example, a.b.c.x()when called, the NullPointerExceptionreason may be:

  • ayes null;
  • a.byes null;
  • a.b.cyes null;

Determining exactly which object was nullpreviously only able to print logs like this:

Starting from Java 14, if generated NullPointerException, the JVM can give detailed information to tell us nullwho the object is. Let’s look at an example:

You can NullPointerExceptionsee similar in the details of ... because "<local1>" is null, meaning the cityfield is null, so we can quickly locate the problem.

This enhanced NullPointerExceptiondetail is new in Java 14, but is off by default, we can -XX:+ShowCodeDetailsInExceptionMessagesenable it by adding a parameter to the JVM:


NullPointerExceptionIt is a common logic error in Java code, which should be exposed and repaired early;

NullPointerExceptionDetailed error information can be viewed by enabling Java 14’s Enhanced Exception Information.

How to use Log4j

Commons Logging was introduced earlier, which can be used as a “log interface”. And the real “logging implementation” can use Log4j.

Log4j is a very popular logging framework, the latest version is 2.x.

Log4j is a component-based log system, and its architecture is roughly as follows:

When we use Log4j to output a log, Log4j automatically outputs the same log to different destinations through different Appenders. E.g:

  • console: output to the screen;
  • file: output to a file;
  • socket: output to a remote computer through the network;
  • jdbc: output to database

In the process of outputting logs, Filter is used to filter which logs need to be output and which logs do not need to be output. For example, only output ERRORlevel logs.

Finally, format the log information through Layout, for example, automatically add information such as date, time, method name, etc.

Although the above structure is complex, when we actually use it, we do not need to care about the API of Log4j, but configure it through the configuration file.

Taking XML configuration as an example, when using Log4j, we can put a log4j2.xmlfile classpathdown to let Log4j read the configuration file and output the log according to our configuration. The following is an example of a configuration file:

Although configuring Log4j is tedious, once configured, it is very convenient to use. For the above configuration file, all INFOlevel logs will be automatically output to the screen, and ERRORlevel logs will not only be output to the screen, but also output to the file at the same time. And, once the log file reaches the specified size (1MB), Log4j will automatically cut the new log file and keep up to 10 copies.

It is not enough to have a configuration file, because Log4j is also a third-party library, we need to download Log4j from here , after decompression, put the following 3 jar packages into classpathit:

  • log4j-api-2.x.jar
  • log4j-core-2.x.jar
  • log4j-jcl-2.x.jar

Because Commons Logging will automatically discover and use Log4j, put the downloaded one in the previous commons-logging-1.2.jarsection classpath.

To print the log, you only need to write it in the way of Commons Logging, without changing any code, you can get the log output of Log4j, similar to:

Best Practices

In the development phase, the Commons Logging interface is always used to write logs, and there is no need to introduce Log4j in the development phase. If you need to write the log to a file, you only need to put the correct configuration file and the jar package related to Log4j classpath, and you can automatically switch the log to use Log4j to write without modifying any code.


According to the configuration file, observe the log file written by Log4j.

commons logging + log4j


Logs are implemented through Commons Logging, and Log4j can be used without modifying the code;

To use Log4j, you only need to put log4j2.xml and related jars into the classpath;

If you want to replace Log4j, you only need to remove log4j2.xml and related jars;

Only when you extend Log4j, you need to refer to the interface of Log4j (for example, the function of encrypting logs and writing them to the database needs to be developed by yourself).