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.

Categories: Java