Getting Exception org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext

后端 未结 2 977
不思量自难忘°
不思量自难忘° 2020-12-05 18:06

My code is very simple using apache-log4j-2.0.2:

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Log4jtest {
  stati         


        
相关标签:
2条回答
  • 2020-12-05 18:17

    Remove below jar's from class path and it should fix the issue -

    log4j-to-slf4j-2.0.2.jar
    log4j-to-slf4j-2.0.2-sources.jar
    log4j-slf4j-impl-2.0.2.jar
    log4j-slf4j-impl-2.0.2-sources.jar
    

    I was able to replicate and fix the issue after downloading apache-log4j-2.0.2 from http://www.apache.org/dyn/closer.cgi/logging/log4j/2.0.2/apache-log4j-2.0.2-bin.zip.

    0 讨论(0)
  • 2020-12-05 18:24

    I was using Maven. I found that declaring my log4j/slf4j dependencies at the top of the <dependencies> list (before Spring Boot, which used logback) fixed the issue.


    To @TheCodingFrog's credit, adding exclusions to my Spring Boot dependencies also solved the problem. Like so:

    <dependencies>
        <dependency>
            <groupId>...</groupId>
            <artifactId>...</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    

    NOTE: If you care about which logging framework is actually used, one perhaps important difference is that with @TheCodingFrog's method, slf4j retained logback as the binding:

    SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
    

    whereas, with the method I used, slf4j/log4j was used:

    SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
    

    In case anyone's interested, the log4j/slf4j dependencies I used are:

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题