I'm new in using the log4j package and I don't see the error:
This is a very simple and straightforward code sample:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class TestLogger {
private static Logger logger;
public static void main(String[] args) {
logger = LogManager.getLogger(TestLogger.class);
logger.info("Hello");
}
}
When I try to compile I get this error:
Exception in thread "main" java.lang.NullPointerException at
org.apache.logging.log4j.LogManager.getLogger(LogManager.java:129) at
my.package.logging.TestLogger.main(TestLogger.java:15)
I am wondering what on earth it's all supposed to mean ...
Could you help here?
You're most probably missing one of the dependencies. This is easy reproducible if you only include in your classpath the log4j-api-2.0-beta1.jar
file.
If you downloaded the binary distribution, include also the log4j-core-2.0-beta1.jar
in your classpath. If your using Maven, put this in your pom.xml
:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta1</version>
</dependency>
The following works for me (updated: now the same as your original posting, but showing the imports)
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class TestLogger
{
private static Logger logger;
public static void main(String[] args) {
logger = LogManager.getLogger(TestLogger.class);
logger.info("Hello");
}
}
provided that you have created a log4j configuration, otherwise you'll get the dreaded error:
log4j:WARN No appenders could be found for logger (TestLogger).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
I solved this problem by avoiding multiple copies on the classpath of the log4j2 jars.
The NPE occurs at Line 129 of LogManager.
(return statement = Line 129)
/**
* Return a Logger with the specified name.
*
* @param name The logger name.
* @return The Logger.
*/
public static Logger getLogger(String name) {
return factory.getContext(LogManager.class.getName(), null, false).getLogger(name);
}
The Problem seems to be, that the factory (LoggerContextFactory) is null = not initialized.
Initialization takes place in a static initializer block in the class LogManager.
My assumption is, that initialization failes when there is more than one LogManager on the classpath.
In my project (a webapplication developed with eclipse) i had the jars in my WEB-INF/lib and referenced by a dependency to another project.
Making ALL references point to the same jars solved that issue in my case.