Home > Net >  Log4j does literally nothing?
Log4j does literally nothing?

Time:03-06

My configuration file is path of the class path. At least I thought it is. I placed the log4j.properties file in the resources folder and log4j does nothing with it. Even if I delete it, no error occurs.

As anyone can see I'm using maven

enter image description here

Content of LoggerTest:

package com.dersimi.stella.logger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LoggerTest {
    public static void main(String[] args) {
        System.out.println("xxx");
        Logger logger = LogManager.getLogger(LoggerTest.class);
        logger.info("Hello this is an info message");
        System.out.println("xxx");
    }
}

Program output:

xxx


xxx

Content of log4j.properties:

log4j.rootLogger=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

In pom.xml is nothing out of the ordinary, just the dependency org.apache.logging.log4j log4j-core 2.17.2, compiler source target is 16, no plugins

CodePudding user response:

The main problem is that you are trying to use log4j (the first one) configurations for log4j2.

In first place make sure you have the following dependencies:

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.17.0</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.17.0</version>
</dependency>

Second, have a file named log4j2.properties with a content like this:

status = warn

appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = LogToConsole

Reference: https://mkyong.com/logging/log4j2-properties-example/

  • Related