I am trying to create a simple logging application in Java using log4j2
.
This is how it looks:
package com.company;
import java.io.IOException;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) throws IOException {
String message = "Hello there!";
System.out.println(message);
logger.info(message);
}
}
There is an error on getLogger
claiming:
Non-static method 'getLogger' cannot be referenced from a static context
I've looked into various threads on this forum but none of them seemed to work. They seemed to declare the logger the same way as I did above.
What am I doing wrong here?
If you're using log4j2
then you imported the wrong LogManager
and Logger
. You should have this:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
You should take a look to the documentation : https://logging.apache.org/log4j/2.x/manual/api.html
According to the documentation Using Log4j in your Apache Maven build, you should have the following dependencies in your pom.xml
:
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
</dependencies>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments