SLF4J - how does it know which log type to use

后端 未结 1 1003
盖世英雄少女心
盖世英雄少女心 2021-02-11 10:42

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 jav

相关标签:
1条回答
  • 2021-02-11 10:43

    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) :

    0 讨论(0)
提交回复
热议问题