SLF4J with Logback in a Maven Project

Why use SLF4J?

When you write a Java library which will be used by unknown consumer, logging is always a problem.You might choose using implementation A, while the consumer uses implementation B.And there are those who use "System.out".. :(SLF4J will resolve this issue.When you use SLF4J you let the consumer decide which logging implementation they want.

Nice API

SLF4J offers an API that was dearly missing in precious implementations.While being very similar to LOG4J using

logger.info("...");logger.debug("...");

It has a built in formatting for strings using the "{}" placeholders.

Original Configuration

Even though SLF4J wraps the API, it leaves the configuration as it was.This means that if you have a project using LOG4J, you can start using SLF4J right away, without modifying your configuration.On the other hand, it means that if you decide to modify the underlying implementation, you would have to rewrite configuration.

Get rid of level checks inside your code

Using SLF4J , like Logback and logging utils, makes the need to check log level redundantOnce you had to write code like

logger.isDebugEnabled(){ logger.debug(" myArg=["+ myArg +"]");}

The need for log level is required since string concatenation had bad performance.SLF4J uses a form of String formatting like so

logger.debug("myArg={}", myArg)

and so there is no string concatenation.With this method, SLF4J can check the log level before formatting the String.

How to print formatted string and exception?

Looking at the API it is not clear how to use

logger.error

to print a formatted string and an exception with stacktrace.You can always use the following

Settings SLF4J with Logback in a Maven Project

Setting up SLF4J with Logback is quite easy.Similar to Log4J settings we will use the resource folder here well.This time we will use a file named "logger.xml" which looks something like this at the root of our resources folder.

Troubleshooting

The most famous problem with SLF4J is when you have multiple implementations available.In this case, it seems there's no way to force SLF4J to use a certain implementation Instead you need to clean you classpath.In Maven, this means you need to exclude transitive dependencies ( those dependencies that originate from other dependencies ).So for example, if you depend on "project-X" which brings LOG4J with it, you should write the following

If you need to find out which dependency brings LOG4J with it, simply use "mvn dependency:tree" command to help you.Go to the folder with the POM, and run this command. You should get output looking like this