SLF4J-如何知道要使用哪种日志类型 [英] SLF4J - how does it know which log type to use
问题描述
SLF4J是包装器/门面类,因此您可以使用许多不同的日志类型,例如logback,log4j等.假设我要同时使用logback和log4j,甚至要同时使用java.util.logging之类的第三个.当我写这样的日志时:
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");
}
}
我怎么知道它使用哪个日志框架?假设我希望它使用logback进行此调用,我怎么知道它不使用其他框架?
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 ?
推荐答案
如您所知,SLF4J只是一个接口,需要一个实现.基本上,SLF4J会调用:
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");
编辑:现在,此信息有些过时了.如今,SLF4J似乎使用java.util.ServiceLoader
加载org.slf4j.spi.SLF4JServiceProvider
,但是逻辑保持不变.
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.
每个与slf4j兼容的日志记录框架都定义了此类.
Every logging framework that is compatible with slf4j defines such a class.
- 如果深入研究
logback
的代码,则会发现一个名为org.slf4j.impl.StaticLoggerBinder
的类,该类将重定向到logback的实现 - 如果深入研究log4j的代码,则没有这样的类,但是在
log4j
和slf4j
之间有一个绑定框架,称为slf4j-log4j
,该框架还定义了一个名为org.slf4j.impl.StaticLoggerBinder
的类,但该类重定向到log4j的实现.
- If you dig into the code of
logback
, you will find a class namedorg.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
andslf4j
which is calledslf4j-log4j
which also define a class namedorg.slf4j.impl.StaticLoggerBinder
but which redirects to log4j's implementation.
因此,如果您希望slf4j使用特定的框架,只需将准确的jar放在类路径中,以便找到org.slf4j.impl.StaticLoggerBinder
的相应实现.
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.
这是全局(来源: http://www.slf4j.org/manual.html ):
这篇关于SLF4J-如何知道要使用哪种日志类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!