0

I'm trying to upgrade an older maven2 project from log4j 1.2 to log4j 2.13. I have added the new dependencies to the pom.xml

[…]
                        <Private-Package>
                            […]
                            org.apache.logging.log4j.*,
                            […]
                        </Private-Package>
[…]
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.13.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.0</version>
        </dependency>

Converting to the new API, I changed the old BasicConfigurator to a call to Configurator.setRootLevel in my main class initialiser. This leads to the following output:

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ClassCastException: org.apache.logging.log4j.simple.SimpleLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
    at org.apache.logging.log4j.core.LoggerContext.getContext(LoggerContext.java:224)
    at org.apache.logging.log4j.core.config.Configurator.setRootLevel(Configurator.java:376)
    at project.Main.<clinit>(Main.java:35)

Per answers to this question, I have also tried adding a configuration file under src/main/resources. This is parsed by log4j and works well for the SimpleLogger it defaults to if I remove the call to Configurator.setRootLevel(). However, I'm still getting the "could not find a logging implementation" regardless of whether I include a configuration file or not.

This is confusing. Despite the first error message, log4j-core is clearly there, as otherwise the ClassCastException could not happen in the first place. I guess I either messed up the pom.xml somewhere, or I should have called something else before calling Configurator.setRootLogger(), but I'm at a loss what it could be.

How can I fix this so log4j detects its implementation and I can programmatically set the logging level without getting an exception?

FWIW, here is a link to the project (without log4j configuration file or use of Configurator), but I'd prefer a general answer as I have one other project which needs updating to log4j 2 as well.

Alexander Klauer
  • 957
  • 11
  • 18
  • I investigated this to the point that I found that you have an OSGI problem which is explained at [Getting log4j2 to work in an OSGI context](https://craftsmen.nl/getting-log4j2-to-work-in-an-osgi-context/). For your purposes I think that it would be simpler for you to use the [Maven Assembly Plugin](http://maven.apache.org/plugins/maven-assembly-plugin/) to build a fat jar instead. – Steve C Jan 27 '20 at 01:14

0 Answers0