-->

LogManager.getLogger() is unable to determine clas

2020-07-01 08:56发布

问题:

I'm using log4j2 (2.11.1) with Java 11 and attempting to get a Logger object using:

private static final Logger LOG = LogManager.getLogger();

(Imported from log4j-api in org.apache.logging.log4j)

At runtime, I receive the following error:

WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.UnsupportedOperationException: No class provided, and an appropriate one cannot be found.
at 
org.apache.logging.log4j.LogManager.callerClass(LogManager.java:555)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:580)
    at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:567)
    at app.App.<clinit>(App.java:11)

Which does make sense - getCallerClass is not supported and so the logger is unable to determine the class name.

Is it supposed to work this way? Surely I don't have to hard-code the class name into each logger?

回答1:

The reason was that the multi-release class files were not being picked up from META-INF/versions/* because I hadn't set the multi-release flag when I built my shaded jar.

I needed to add:

Multi-Release:true

To my manifest, and everything started working.



回答2:

The answer by @DanielScott is correct. When using the Gradle Shadow plugin, I added the following to my build.gradle to appended the Multi-Release:true flag to the manifest.

jar {
    manifest {
        attributes 'Multi-Release': 'true'
    }
}