如果您查看slf4j-api的源代码(任何现代版本,比如1.7.5),就会有一个LoggerFactory类,其方法如下:
private static Set findPossibleStaticLoggerBinderPathSet() {
// use Set instead of list in order to deal with bug #138
// LinkedHashSet appropriate here because it preserves insertion order during iteration
Set staticLoggerBinderPathSet = new LinkedHashSet();
try {
ClassLoader loggerFactoryClassLoader = LoggerFactory.class
.getClassLoader();
Enumeration paths;
if (loggerFactoryClassLoader == null) {
paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
} else {
paths = loggerFactoryClassLoader
.getResources(STATIC_LOGGER_BINDER_PATH);
}
while (paths.hasMoreElements()) {
URL path = (URL) paths.nextElement();
staticLoggerBinderPathSet.add(path);
}
} catch (IOException ioe) {
Util.report("Error getting resources from path", ioe);
}
return staticLoggerBinderPathSet;
}当您调用任何Logger方法(调试、信息、警告、错误等)时,都会调用此方法。而且SLF4J绑定还没有初始化。这就是SLF4J如何确定在运行时使用哪个绑定。
基本上,为SLF4J编写正确绑定的一种方法是实现您自己的org.slf4j.impl.StaticLoggerBinder类。然而,slf4j-api JAR还附带了它自己的虚拟org.slf4j.impl.StaticLoggerBinder实现,这可能是为了防止在SLF4J开发过程中出现编译器错误(如果绑定没有提供这样的StaticLoggerBinder,则充当无操作备份)。
因此,如果运行时类路径上有slf4j-api-1.7.5和slf4j-simple-1.7.5,那么当您第一次使用Logger#info(String)时,将选择slf4j-simple JAR中定义的StaticLoggerBinder而不是slf4j-api JAR中定义的StaticLoggerBinder。
--我正在尝试理解这个“首选项”/prioritization(绑定impl而非api )是如何工作的。
提前感谢!
发布于 2013-10-28 11:40:31
虚拟StaticLoggerBinder根本不包含在slf4j-api jar文件中。
请参阅slf4j-api源代码pom.xml中的这里。虚拟活页夹被删除了。
https://stackoverflow.com/questions/17706190
复制相似问题