SLF4J - how does it know which log type to use

2019-04-03 00:24发布

问题:

SLF4J is a wrapper/facade class so you can use many different log types, such as logback, log4j , etc. Let's say i want to use both logback and log4j and even a third like java.util.logging. when i write a log like this:

    public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

How do i know which logging framework its using ? Let's say i want it to use logback for this call, how do i know its not using another framework ?

回答1:

As you understood, SLF4J is only an interface and needs an implementation. Basically, SLF4J does a call to :

ClassLoader.getSystemResources("org/slf4j/impl/StaticLoggerBinder.class");

EDIT : now, this information is a bit outdated. It seems that nowadays, SLF4J uses java.util.ServiceLoader to load a org.slf4j.spi.SLF4JServiceProvider but the logic stays the same.

It means that you classpath must contain such a class with this fully qualified name.

Every logging framework that is compatible with slf4j defines such a class.

  • If you dig into the code of logback, you will find a class named org.slf4j.impl.StaticLoggerBinder which redirects to logback's implementation
  • If you dig into the code of log4j, there is not such class but there is a binding framework between log4j and slf4j which is called slf4j-log4j which also define a class named org.slf4j.impl.StaticLoggerBinder but which redirects to log4j's implementation.

So if you want slf4j to use a particular framework, just place the accurate jar in the classpath so that the corresponding implementation of org.slf4j.impl.StaticLoggerBinder is found.

Here is the big picture (Source : http://www.slf4j.org/manual.html) :