Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - Non-static method 'getLogger' cannot be referenced from a static context

Tags:

java

logging

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?

like image 923
Daredevil Avatar asked Oct 16 '25 17:10

Daredevil


1 Answers

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

EDIT: Maven

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>
like image 126
Mickael Avatar answered Oct 19 '25 07:10

Mickael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!