Tag Archives: SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.

       Recently, when learning springboot, sometimes it is clear that there is no problem with the project running, but the console will report an error, such as the following problem exception prompt:

        From this, we can see that the main error is the jar package of slf4j, and “failed to load class’ org.slf4j.impl.staticloggerbinder” in the fault code means “failed to load class file org.slf4j.impl.staticloggerbinder”.

The solution published on the official website is:

        This error is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

Translated as follows:

This error was reported when org.slf4j.impl. The staticloggerbinder class cannot be loaded into memory. When this happens, the appropriate slf4j binding classpath cannot be found. The classpath of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar should solve this problem.

        Therefore, the solution is to load the dependency of one of the above package files (and only one) in the POM file of Maven project. At this time, I load the dependency of “slf4j-nop-1.7.2. Jar” package file, and then the whole project can be compiled without exception.

  1 <dependency>
  2     <groupId>org.slf4j</groupId>
  3     <artifactId>slf4j-nop</artifactId>
  4     <version>1.7.2</version>
  5 </dependency>

[Solved] SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”

The following is the process of learning Java and debugging

The log is changed to slf4j + logback, and no log file is generated locally. During debugging, an error prompt is found (it appears when loading the Druid)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

It is said on the Internet that the actual log implementation package is not configured, but it is configured in pom.xml

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.26</version>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
      <scope>test</scope>  // noticed
    </dependency>

find the error codes:com\alibaba\druid\1.1.16\druid-1.1.16-sources.jar!\com\alibaba\druid\pool\DruidAbstractDataSource.java

public abstract class DruidAbstractDataSource extends WrapperAdapter 
implements DruidAbstractDataSourceMBean, DataSource, DataSourceProxy, Serializable 
{
    private static final long serialVersionUID = 1L;
    private final static Log  LOG  = LogFactory.getLog(DruidAbstractDataSource.class); // 此处
	...
}

com\alibaba\druid\1.1.16\druid-1.1.16-sources.jar!\com\alibaba\druid\support\logging\LogFactory.java

public class LogFactory {

    private static Constructor logConstructor;

    static {
        String logType= System.getProperty("druid.logType");
        if(logType != null){
            if(logType.equalsIgnoreCase("slf4j")){
                tryImplementation("org.slf4j.Logger", "com.alibaba.druid.support.logging.SLF4JImpl");
            }else if(logType.equalsIgnoreCase("log4j")){
                tryImplementation("org.apache.log4j.Logger", "com.alibaba.druid.support.logging.Log4jImpl");
            }else if(logType.equalsIgnoreCase("log4j2")){
                tryImplementation("org.apache.logging.log4j.Logger", "com.alibaba.druid.support.logging.Log4j2Impl");
            }else if(logType.equalsIgnoreCase("commonsLog")){
                tryImplementation("org.apache.commons.logging.LogFactory",
                        "com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
            }else if(logType.equalsIgnoreCase("jdkLog")){
                tryImplementation("java.util.logging.Logger", "com.alibaba.druid.support.logging.Jdk14LoggingImpl");
            }
        }
        // Prefer log4j, rather than Apache Common Logging. Because the latter can not set the information of the real Log caller
        tryImplementation("org.slf4j.Logger", "com.alibaba.druid.support.logging.SLF4JImpl"); // here
        tryImplementation("org.apache.log4j.Logger", "com.alibaba.druid.support.logging.Log4jImpl");
        tryImplementation("org.apache.logging.log4j.Logger", "com.alibaba.druid.support.logging.Log4j2Impl");
        tryImplementation("org.apache.commons.logging.LogFactory",
                          "com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
        tryImplementation("java.util.logging.Logger", "com.alibaba.druid.support.logging.Jdk14LoggingImpl");

        if (logConstructor == null) {
            try {
                logConstructor = NoLoggingImpl.class.getConstructor(String.class);
            } catch (Exception e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }
}

private static void tryImplementation(String testClassName, String implClassName) {
	if (logConstructor != null) {
		return;
	}

	try {
		Resources.classForName(testClassName);
		Class implClass = Resources.classForName(implClassName);
		logConstructor = implClass.getConstructor(new Class[] { String.class });

		Class<?> declareClass = logConstructor.getDeclaringClass();
		if (!Log.class.isAssignableFrom(declareClass)) {
			logConstructor = null;
		}

		try {
			if (null != logConstructor) {
				logConstructor.newInstance(LogFactory.class.getName()); // here
			}
		} catch (Throwable t) {
			logConstructor = null;
		}

	} catch (Throwable t) {
		// skip
	}
}

com\alibaba\druid\1.1.16\druid-1.1.16-sources.jar!\com\alibaba\druid\support\logging\SLF4JImpl.java

public class SLF4JImpl implements Log {

    private static final String callerFQCN = SLF4JImpl.class.getName();
    private static final Logger testLogger = LoggerFactory.getLogger(SLF4JImpl.class); // here
    static {
        // if the logger is not a LocationAwareLogger instance, it can not get correct stack StackTraceElement
        // so ignore this implementation.
        if (!(testLogger instanceof LocationAwareLogger)) {
            throw new UnsupportedOperationException(testLogger.getClass() + " is not a suitable logger");
        }
    }
	...
}

org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26-sources.jar!\org\slf4j\LoggerFactory.java

public static Logger getLogger(Class<?> clazz) {
        Logger logger = getLogger(clazz.getName()); // 此处
        if (DETECT_LOGGER_NAME_MISMATCH) {
            Class<?> autoComputedCallingClass = Util.getCallingClass();
            if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {
                Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),
                                autoComputedCallingClass.getName()));
                Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
            }
        }
        return logger;
    }

    public static Logger getLogger(String name) {
        ILoggerFactory iLoggerFactory = getILoggerFactory(); // here
        return iLoggerFactory.getLogger(name);
    }

public static ILoggerFactory getILoggerFactory() {
        if (INITIALIZATION_STATE == UNINITIALIZED) {
            synchronized (LoggerFactory.class) {
                if (INITIALIZATION_STATE == UNINITIALIZED) {
                    INITIALIZATION_STATE = ONGOING_INITIALIZATION;
                    performInitialization(); // here
                }
            }
        }
        switch (INITIALIZATION_STATE) {
        case SUCCESSFUL_INITIALIZATION:
            return StaticLoggerBinder.getSingleton().getLoggerFactory();
        case NOP_FALLBACK_INITIALIZATION:
            return NOP_FALLBACK_FACTORY;
        case FAILED_INITIALIZATION:
            throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
        case ONGOING_INITIALIZATION:
            // support re-entrant behavior.
            // See also http://jira.qos.ch/browse/SLF4J-97
            return SUBST_FACTORY;
        }
        throw new IllegalStateException("Unreachable code");
    }

    private final static void performInitialization() {
        bind(); // here
        if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
            versionSanityCheck();
        }
    }

private final static void bind() {
        try {
            ...
            // skip check under android, see also
            // http://jira.qos.ch/browse/SLF4J-328
            if (!isAndroid()) {
                staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); // here
                reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
            }
            ...
        } catch () {
			...
        } 
    }

static Set<URL> findPossibleStaticLoggerBinderPathSet() {
        // use Set instead of list in order to deal with bug #138
        // LinkedHashSet appropriate here because it preserves insertion order
        // during iteration
        Set<URL> staticLoggerBinderPathSet = new LinkedHashSet<URL>();
        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);
            }
            while (paths.hasMoreElements()) {
                URL path = paths.nextElement();
                staticLoggerBinderPathSet.add(path);
            }
        } catch (IOException ioe) {
            ...
        }

		return staticLoggerBinderPathSet; // The returned size is zero
    }

Found the build directory, missing logback-classic-1.2.3.jar

It turns out that the impact of POM. XML (this code is copied directly from Maven)

In the end, it’s the influence of this sentence, or the foundation is not laborious