My Profile Photo

Cory Kelly


CoryPlusPlus - Cory with classes


A blog documenting solutions to some interesting problems


SLF4J vs Log4j

During a recent refactor of a relatively large code base, I found myself in logging hell. There were multiple log implementations and jar files on the classpath being imported from many different maven dependencies. That coupled with my lack of full comprehension on logger implementations made the task very difficult for me. This post will hopefully save you some time and headache.

So what is the difference between Log4j and SLF4J.

Simply Log4j is a concrete implementation of a logging solutions and SLF4J is abstracted implementation.

The above line should already tell you that SLF4J is more powerful, just for the simple fact that it isn’t concrete. Let’s say for example that initially you decide that you want to go with logback for your logging implementation. So you code for two months and initialize loggers using logback specific libraries all throughout your code. Things are working great for you, until you realize logback doesn’t offer you the configuration flexibility that you had hoped for. You decide that you want to switch to log4j instead.

In order to switch to log4j you will need to make lots of code changes. Changing the lines where your logger is instantiated and perhaps even code modifications to each line you are outputting (log.error, log.info, etc)

This is a hassle and with very large products can introduce the potential for data loss!

Now, had you implemented your logging solutions using SLF4J, you simply could have changed a few maven dependencies and everything would have worked with NO CODE CHANGES. That is the beauty of SLF4J.

Also the following is useful to know. slf4j-over-log4j.jar will convert all your slf4j statements to log4j. log4j-over-slf4j.jar will convert all your log4j statements to slf4j.

If you have both on your classpath you with cause an infinite loop and your program will not run. There are many spring mvn artifacts that package both, so determine the one you need and exclude instances of the one you do not need.

comments powered by Disqus