Log4j 2 - XML configuration example

Posted on May 1, 2017

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

Tools and technologies used for this example are-

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

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 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">






XML configuration file for Log4j 2

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


<?xml version="1.0" encoding="UTF-8"?>

    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
        pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />

    <!-- File Appender -->
    <File name="File" fileName="c:/log/app.log">
        pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />

    <Root level="trace">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />

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 JSON configuration file.

View an equivalent - Log4j 2 YAML 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-01 17:07:41 PM [main] TRACE com.boraji.tutorial.log4j2.MainApp - Entering application...
2017-May-01 17:07:41 PM [main] INFO  com.boraji.tutorial.log4j2.MainApp - Hello Log4j2...
2017-May-01 17:07:41 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-01 17:07:41 PM [main] TRACE com.boraji.tutorial.log4j2.MainApp - Exiting application...


Download Sources