slf4j mechanism of loading its impl

86 views Asked by At

When you use slf4j and want to use it with log4j, you just put the log4j jar file in classpath and without any configuration slf4j understand it's impl. How slf4j do that? what is the mechanism here?

1

There are 1 answers

0
Nick Holt On

First let me clarify a few points:

  • SLF4J defines a standard logging API (harder than you'd think if the number of logging APIs are anything to go by).
  • while there can be many implementations of SLF4J, the common one is Logback.
  • historically there has been several attempts at logging APIs, these logging APIs have in turn have been used by other APIs you may use in your project - for example Spring usings Commons Logging.

It this last point that's important. Within a project you may use a number of 3rd party APIs each of which use one of the popular logging APIs (Log4J, Commons, JDK, etc). This is a pain because you have to configure each individually.

The solution is to use SLF4J, which provides reimplementations for the legacy logging APIs, which delegate to SLF4J. Hence when whichever 3rd party APIs you use makes a logging call, that call is delegated to SLF4J by the SLF4J implementation of a particular logging API.

And so the mechanism being used is delegation combined with the fact that Java inherently uses the first class it loads from the classpath (in this case the reimplementation of a particular logging API). So as long as the Logging classes in the reimplementation match the definition the calling code was compiled against, the calling code is none the wiser.