启动Spring Boot项目时,会遇到如下关于slf4j相关的日志异常情况,导致项目无法启动。
    相关异常信息如下:

    1. Exception in thread "main" java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.impl.Log4jLoggerFactory loaded from file:~/.m2/repository/org/slf4j/slf4j-log4j12/1.7.30/slf4j-log4j12-1.7.30.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.impl.Log4jLoggerFactory
    2. at org.springframework.util.Assert.instanceCheckFailed(Assert.java:696)
    3. at org.springframework.util.Assert.isInstanceOf(Assert.java:596)

    很明显项目中并没有用到所谓的weblogic.xml,那么怎么会报关于WEB-INF/weblogic.xml配置的异常呢?
    其中关键新增在这里:

    1. LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation……

    就是说Logback已经在classpath中存在,但LoggerFactory并不是Logback的相关日志上线文内容。此时就应该意识到有Logback依赖冲突。

    此时,可用过查看maven依赖来排查问题,在项目跟目录执行如下命令:

    1. mvn dependency:tree

    展示结果内容如下:

    1. [INFO] +- org.springframework.boot:spring-boot-starter:jar:1.3.3.RELEASE:compile
    2. [INFO] | +- org.springframework.boot:spring-boot:jar:1.3.3.RELEASE:compile
    3. [INFO] | +- org.springframework.boot:spring-boot-autoconfigure:jar:1.3.3.RELEASE:compile
    4. [INFO] | +- org.springframework.boot:spring-boot-starter-logging:jar:1.3.3.RELEASE:compile
    5. [INFO] | | +- ch.qos.logback:logback-classic:jar:1.1.5:compile
    6. [INFO] | | | \- ch.qos.logback:logback-core:jar:1.1.5:compile
    7. [INFO] | | +- org.slf4j:jcl-over-slf4j:jar:1.7.5:compile
    8. [INFO] | | +- org.slf4j:jul-to-slf4j:jar:1.7.5:compile
    9. [INFO] | | \- org.slf4j:log4j-over-slf4j:jar:1.7.5:compile
    10. [INFO] | +- org.springframework:spring-core:jar:4.2.5.RELEASE:compile
    11. [INFO] | \- org.yaml:snakeyaml:jar:1.16:compile
    12. ...
    13. [INFO] +- org.slf4j:slf4j-log4j12:jar:1.7.5:compile
    14. [INFO] | \- org.slf4j:slf4j-api:jar:1.7.5:compile

    很显然,可以看出多处引用了同样的slf4j-api的jar包。也就是jar包冲突了,此时将依赖的jar包排除掉,只有一处即可。

    如果是springboot中的jar包无效可使用如下方式排除:

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter</artifactId>
    4. <exclusions>
    5. <exclusion>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-logging</artifactId>
    8. </exclusion>
    9. </exclusions>
    10. </dependency>

    如果是其他依赖库的jar包无效则可通过同样的方式排除:

    1. <dependency>
    2. <groupId>com.github.secbr</groupId>
    3. <artifactId>fastdfs-client-plus</artifactId>
    4. <version>1.1.1-RELEASE</version>
    5. <exclusions>
    6. <exclusion>
    7. <groupId>org.slf4j</groupId>
    8. <artifactId>slf4j-log4j12</artifactId>
    9. </exclusion>
    10. </exclusions>
    11. </dependency>

    然后再重新启动springboot项目,项目便可正常启动。