Home > Software design >  Unable to configure log4j2 for logging in Maven project on VS Code
Unable to configure log4j2 for logging in Maven project on VS Code

Time:12-27

I have added the dependencies in pom.xml: log4j-api (2.17.0) and log4j-core (2.17.0).

Java version on Windows 10 is "17.0.1" 2021-10-19 LTS

I have put the file log4j2.yml is src/main/resources folder. But it appears that this file is never read. I am able to log to console but it's not formatted based on what I have configured in log file. Likewise, I can't log to file since config file is never read.

I am using Maven on VS Code. App itself is rather simple:

package com.example;

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

/**
 * Hello world!
 *
 */
public class App 
{
    private static final Logger logger = LogManager.getLogger(App.class);

    public static void main( String[] args )
    {
        logger.error("Hello Logger!");
        System.out.println( "Hello World!" );
    }
}

Actual output on execution is as follows:

C:\Users\userme\Documents\workspace\java-sample> c: && cd c:\Users\userme\Documents\workspace\java-sample && cmd /C ""C:\Program Files\Java\jdk-17.0.1\bin\java.exe" -XX: ShowCodeDetailsInExceptionMessages @C:\Users\USERME\AppData\Local\Temp\cp_a2ngr445g97bq5yjwdq9bbcx.argfile com.example.App "        
23:13:36.471 [main] ERROR com.example.App - Hello Logger!
Hello World!

YAML file:

Configuration:
  name: Default
  Properties:
    Property:
      name: log-path
      value: "logs"
  Appenders:
    Console:
      name: Console_Appender
      target: SYSTEM_OUT
      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
    File:
      name: File_Appender
      fileName: ${log-path}/logfile.log
      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
  Loggers:
      Root:
        level: debug
        AppenderRef:
          - ref: Console_Appender
      Logger:
        - name: com.example.App
          level: debug
          AppenderRef:
            - ref: File_Appender
              level: debug

CodePudding user response:

"Fine print hero" struck again! :-) From log4j2 Configuration reference:

Additional runtime dependencies are required for using YAML configuration files.

These are (as of today):

<jackson.version>2.14</jackson.version> <!-- 2021/12/26(, merry x-mas!) -->
<!-- ... -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
<scope>runtime</scope> <!-- ! -->
<!-- ... -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<!-- As: -->
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<!-- ... -->
  • Related