本人想在项目中加入log系统,采用slf4j+log4j的框架,在集成到项目中时,遇到了2个问题,记录下来。
multiple SLF4J bindings
错误日志
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/Administrator/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-log4j12/1.7.21/7238b064d1aba20da2ac03217d700d91e02460fa/slf4j-log4j12-1.7.21.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/Administrator/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-slf4j-impl/2.11.2/4d44e4edc4a7fb39f09b95b09f560a15976fa1ba/log4j-slf4j-impl-2.11.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
问题解决
项目通过gradle引入了多个依赖项目,这些依赖项目又引入了slf4j-log4j12和log4j-slf4j-impl,这两个jar包都有StaticLoggerBinder类,所以出现了multiple bindings。log4j-slf4j-impl是我主动引入的,而slf4j-log4j12是依赖项目引入的,所以必须要找出是哪个依赖库引入了slf4j-log4j12。下面介绍下在idea中的方法(我用的是gradle,maven类似):
1.打开Gradle projects,找到dependences task,执行它,会输出gradle的依赖树:
然后在依赖树的输出里查找slf4j-log4j12:
发现它是由zookeeper3.6.2引入的,所以我们可以在gradle的配置里加上这段代码把它排除:
configurations.all {
exclude module: 'slf4j-log4j12'
}
以上代码是斩草除根型的解决办法,如果以后再引入别的依赖,也包含slf4j-log4j12的话仍然起效。如果想精确一点,只针对zookeeper这个依赖,也可以这么写:
dependencies {
compile('io.vertx:vertx-zookeeper:3.6.2') {
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}
//...
}
log4j找不到配置文件
错误日志
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
问题解决
log4j的配置文件需要从system property里面读取,可以在系统的启动方法里加上一行代码:
System.setProperty("log4j.configurationFile","log4j.xml");
有个地方要注意,log4j默认是到你的classpath下去找xml配置文件的,所以你在上面代码里写的“log4j.xml”,其实log4j是从classpath的目录里挨个查找log4j.xml。如果你没有有maven或gradle,那么可以把log4j.xml放在src目录,如果用maven或gradle,那么放在src/main/resources。