slf4j如何绑定到Logging Framework

How does slf4j bind to the Logging Framework

我正在经历 slf4j code to understand the binding process when I stumbled upon the bind() method in the LoggerFactory class

感兴趣的代码片段:

        if (!isAndroid()) {
            staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
            reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
        }
        // the next line does the binding
        StaticLoggerBinder.getSingleton();
        INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
        reportActualBinding(staticLoggerBinderPathSet);
        replayEvents();

方法findPossibleStaticLoggerBinderPathSet()是这样的:

private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
try {
        ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
        Enumeration<URL> paths;
        if (loggerFactoryClassLoader == null) {
            paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
        } else {
            paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
        }

自默认slf4j-api package provides a class with name StaticLoggerBinder with some defaults and depends on the actual implementations provided by the Binding Projects (log4j、logback等)。

它如何实际识别要使用哪个 StaticLoggerBinder class?

好吧,StaticLoggerBinder 在 slf4j-api 的源代码中,但它已被删除,因此它不会最终出现在 jar 中。如果您下载 JAR,您会发现它不存在。