log4j-over-slf4的log4j Loger加载问题
程序员文章站
2023-12-28 09:05:58
...
log4j-over-slf4是通过定义和log4j同包名的org.apache.log4j.Logger来实现替换log4j的,但log4j-over-slf4怎么能确定JVM一定会加载它定义的这个Logger?
做了一个测试,发现在classpath中,log4j和slf4j两个包谁在前面先加载:
/home/yunpeng/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar:
/home/yunpeng/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.4/log4j-over-slf4j-1.7.4.jar
测试代码
package com.taobao.hasf.tlog.proxy.gather; import org.apache.log4j.Logger; public class LogGathersTester { public static void main(String[] args) throws InterruptedException { System.out.println(Boo.test); System.out.println(Logger.getLogger("root")); Thread.currentThread().join(); }
测试脚本:
slf4j在前
/duitang/dist/sys/java/bin/java -Dfile.encoding=UTF-8 -classpath /duitang/dist/app/branches/tlog/tlog-proxy/target/test-classes:/duitang/dist/app/branches/tlog/tlog-proxy/target/classes:/home/yunpeng/.m2/repository/org/slf4j/slf4j-api/1.7.4/slf4j-api-1.7.4.jar:/home/yunpeng/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.4/log4j-over-slf4j-1.7.4.jar:/home/yunpeng/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar com.taobao.hasf.tlog.proxy.gather.LogGathersTester
hello
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.
org.apache.log4j.Logger@37dd7056
hello
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.
org.apache.log4j.Logger@37dd7056
log4j在前
/duitang/dist/sys/java/bin/java -Dfile.encoding=UTF-8 -classpath /duitang/dist/app/branches/tlog/tlog-proxy/target/test-classes:/duitang/dist/app/branches/tlog/tlog-proxy/target/classes:/home/yunpeng/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar:/home/yunpeng/.m2/repository/org/slf4j/slf4j-api/1.7.4/slf4j-api-1.7.4.jar:/home/yunpeng/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.4/log4j-over-slf4j-1.7.4.jar: com.taobao.hasf.tlog.proxy.gather.LogGathersTester
hello
org.apache.log4j.Logger@12276af2
hello
org.apache.log4j.Logger@12276af2
那么在tomcat容器中如何能保证一定先加载log4j-over-slf4j包中定义的Logger呢?
解决办法:
应用只依赖log4j-over-slf4j,不过有点风险,参考:http://*.com/questions/4028703/issues-replacing-log4j-with-logback-log4j-over-slf4j-jar-shortcomings