我用的Spring Boot maven構建的工程,默認引入了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
再引入webmagic相關的包之后,運行出現大量的debug日志。
此時沒有加入任何的log配置文件
代碼初始化執行時報以下警告
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/hongbo/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/hongbo/.m2/repository/org/slf4j/slf4j-log4j12/1.7.25/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
說明有其他dependency引入了logback
根據作者的說明:
WebMagic 使用slf4j-log4j12作為slf4j的實現.如果你自己定制了slf4j的實現,請在項目中去掉此依賴。
<exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> </exclusions>
查看maven tree
發現

該包是在spring-boot-starter被引入的,所以需要做排除。
但是不能直接排除spring-boot-starter-logging,這樣則所有依賴於slf4j的也將失效。
所以排除logback-classic即可
如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency>
關於有多個log的實現及其實際綁定的log配置文件。
通常,我們會使用以下三種log
log4j,對應配置文件log4j.xml或log4j.properties
logback, 對應配置文件logback.xml
log4j2, 對應配置文件log4j2.xml或log4j2.json
但是在引用log4j2時有個陷阱或者小細節
當直接依賴log4j2時,其對應的配置文件為log4j2.xml或log4j2.json
其依賴如下
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.7</version> </dependency>
當使用slf4j-log4j12時,其對應的配置文件為log4j.xml或log4j.properties
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency>
當項目中存在多個log依賴,且沒有排除相應的依賴的時候,會選擇哪個配置文件呢?
想maven加載沖突jar有沒有加載順序(偷懶),在官網查了下:點擊打開鏈接
The way SLF4J picks a binding is determined by the JVM and for all practical purposes should be considered random.
說明slf4j具體選哪個binding是jvm隨機決定的。那么偷懶(調整先后順序)不成,再繼續。
雖然SLF4J隨機binding了一個log,但是SLF4J會告訴我們它到底binding了誰。
通過項目啟動的時候,查看SLF4J: Actual binding is of type
例如SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
說明依賴的是Log4j對應的配置文件
當實際綁定的為logback且logback.xml不存在時,springboot默認會輸出debug級別的日志。
參考:
spring boot log4j2配置不生效
Maven全局排除某引用的一種方式