获取exceptionorg.apache.logging.slf4j.SLF4JLoggerContext无法强制转换为org.apache.logging.log4j.core.LoggerContext

使用apache-log4j-2.0.2我的代码非常简单:

import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; public class Log4jtest { static Logger log =Logger.getLogger(Log4jtest.class); public static void main(String[] args) { BasicConfigurator.configure(); log.debug("This is debug message"); } } 

但我得到的例外是:

 Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext`` at org.apache.log4j.Logger.getLogger(Logger.java:41) at Log4jtest.(Log4jtest.java:11) 

为什么exception来自一个简单的程序?

从类路径中删除jar的下方,它应该解决问题 –

 log4j-to-slf4j-2.0.2.jar log4j-to-slf4j-2.0.2-sources.jar log4j-slf4j-impl-2.0.2.jar log4j-slf4j-impl-2.0.2-sources.jar 

从http://www.apache.org/dyn/closer.cgi/logging/log4j/2.0.2/apache-log4j-2.0.2下载apache-log4j-2.0.2后,我能够复制并解决问题。 -bin.zip 。

我在使用Maven。 我发现在列表的顶部(在使用logback Spring Boot之前)声明我的log4j / slf4j依赖项修复了这个问题。


对于@TheCodingFrog来说,在我的Spring Boot依赖项中添加排除项也解决了这个问题。 像这样:

   ... ...   log4j *   org.slf4j *   org.apache.logging.log4j *     

注意:如果您关心实际使用的是哪个日志框架 ,可能的一个重要区别是使用@TheCodingFrog的方法, slf4j保留了作为绑定的logback

 SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder] 

然而,根据我使用的方法,使用了slf4j / log4j

 SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory] 

如果有人感兴趣,我使用的log4j / slf4j依赖项是:

  log4j log4j 1.2.17   org.slf4j slf4j-api 1.7.7   org.slf4j slf4j-log4j12 1.7.7