SLF4j Vs Log4j – Which one is better?

I have been asked this question multiple times, so I thought to write down my answer as this post in blog itself so others can refer to it from time to time, when needed.

Simple Logging Facade for Java (SLF4J) is an API designed to give generic access to many logging frameworks; log4j being one of them. Which one you use, is then decided at deployment time, not when you write your code. Best practice is to use slf4j to for your own log statements, and then choose the appropriate backend for it (including log4j as well by configuring to use log4j as a logging backend).

For example, below code you may write in your application class files:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld
    public static void main(String[] args)
        Logger logger = LoggerFactory.getLogger(HelloWorld.class);"Hello World");

Now all you have to choose, which logging framework you need to use in runtime. For that, you will have to include two jar files:

  1. SLF4j binding jar file
  2. Desired logging framework jar files

e.g. to use log4j in your project, you will have to include below given jar files:

  • slf4j-log4j12-1.7.12.jar
  • log4j-1.2.17.jar

Once you have places both jar files in your application classpath, SLF4j will automatically detect it and start using log4j for processing the log statements based on configuration you provided in log4j configuration file.

In future, if you want to replace log4j with any other logging framework – All you have to do is replace the binding and logging jar files (along with configuration file). It’s easy. No need to change the actual source code files.

So essentially, SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your application and make it easy to replace it in future with more capable library.

I hope that above discussion will help some of us in future.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “SLF4j Vs Log4j – Which one is better?”

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.