slf4j+log4j2在tomcat8 下无日志输出

时间:2020-12-20 21:50:56

http://blog.mugbya.cn/2014/10/25/slf4j-tomcat/

 在写这个问题之前,先声明,这个问题肯定不是大家都能遇到,只是特性条件会出现这个情况,因了解还不是太深入,目前只记录我了解的所有.

  在问题的版本差异比较时,慢慢发现一些问题:

// tomcat7 SLF4J: Found binding in [jar:file:~/project/out/artifacts/cjtrade_Web_exploded/WEB-INF/lib/log4j-slf4j-impl-2.0.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:~/project/out/artifacts/cjtrade_Web_exploded/WEB-INF/lib/slf4j-log4j12-1.7.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]

// tomcat8 SLF4J: Found binding in [jar:file:~/project/out/artifacts/cjtrade_Web_exploded/WEB-INF/lib/slf4j-log4j12-1.7.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:~/project/out/artifacts/cjtrade_Web_exploded/WEB-INF/lib/log4j-slf4j-impl-2.0.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]

  如果认真对比,你会发现slf4j找到了两个实现的类,但是在不同的版本它们的顺序却不一样. 结合slf4j实际绑定的类型

// tomcat 7
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).

// tomcat 8
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).

  找到的绑定类的都是一样,但在不同的包下,这两个都实现了,来分别看下这两个包:

slf4j+log4j2在tomcat8 下无日志输出 log4j-slf4j-impl

slf4j+log4j2在tomcat8 下无日志输出 slf4j-log4j12.png

针对于slf4j跟log4j2搭配,log4j2官网有明确指出:

Use of the Log4j 2 SLF4J Binding (log4j-slf4j-impl-2.0.jar) together with the SLF4J adapter (log4j-to-slf4j-2.0.jar) should never be attempted, as it will cause events to endlessly be routed between SLF4J and Log4j 2.

所以我们应该确信用log4j-slf4j-impl这一个jar,但是slf4j-log4j12这一个是怎么回事呢,在slf4j官网上有这样的叙述:

slf4j-log4j12-1.7.7.jar
Binding for log4j version 1.2, a widely used logging framework. You also need to place log4j.jar on your class path.

从这来看,不是这个版本才对.当我们在maven中删除这个依赖,但是好像还是会有默认的依赖(1.7.6)存在.所以我们只能去lib移除了它了.这样只让slf4j绑定log4j-slf4j-impl包下的org.apache.logging.slf4j.Log4jLoggerFactory就解决了

  至于为什么tomcat8 跟 tomcat7 会加载顺序不一样,这点我还是没懂.了解的太少了,只知道7跟8差异很大,你去比较conf/catalina.properties这个文件你就知道了