Log4j 2 - YAML configuration example

Posted on May 2, 2017

In this post, you will learn how to configure the Log4j 2 API in a java application using YAML configuration file.

Tools and technologies used for this example are-

  • JDK 1.8.0_121
  • Maven 3.3.9
  • Eclipse Neon.3
  • Log4j 2.8.2
  • Jackson API 2.8.7

Project structure

Review the following maven project structure.


Refer this article to learn - How to create a maven project in eclipse.

Jar dependencies

Edit pom.xml file and add log4j2 and Jackson API dependencies in it as follows.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">







YAML configuration file for Log4j 2

Create a log4j2.yaml file under src/main/resources source folder and write the following code in it.


        pattern: '%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n'
      name: Console
      target: SYSTEM_OUT
        pattern: '%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n'
      name: File
      fileName: c:/log/app.log
      - ref: Console
      - ref: File
      level: trace

Console Appender - Writes the logs to either System.out or System.err.

File Appender - Writes the logs to the File named in the fileName parameter.

View an equivalent - Log4j 2 XML configuration file.

View an equivalent - Log4j 2 JSON configuration file.

Test Log4j 2 configuration

Create a main class to test the above log4j 2 configuration.


package com.boraji.tutorial.log4j2;

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

public class MainApp {

   private static final Logger logger = LogManager.getLogger(MainApp.class);

   public static void main(String[] args) {

      logger.trace("Entering application...");

      logger.info("Hello Log4j2...");
      logger.error("Something is wrong with this code", new Exception("Invalid message"));

      logger.trace("Exiting application...");

After executing the MainApp.java the console output and c:/log/app.log file will look like as follows.

2017-May-02 21:52:26 PM [main] TRACE com.boraji.tutorial.log4j2.MainApp - Entering application...
2017-May-02 21:52:26 PM [main] INFO  com.boraji.tutorial.log4j2.MainApp - Hello Log4j2...
2017-May-02 21:52:26 PM [main] ERROR com.boraji.tutorial.log4j2.MainApp - Something is wrong with this code
java.lang.Exception: Invalid message
	at com.boraji.tutorial.log4j2.MainApp.main(MainApp.java:15) [classes/:?]
2017-May-02 21:52:26 PM [main] TRACE com.boraji.tutorial.log4j2.MainApp - Exiting application...