Log4j2 XML Configuration Example

Apache Log4j2 is an upgrade to Log4j 1.x that provides significant improvements over its predecessor such as performance improvement, automatic reloading of modified configuration files, Java 8 lambda support and custom log levels.

Log4j 2.4 and greater requires Java 7. Versions 2.0-alpha1 to 2.3 required Java 6.

1. Log4j2 Maven Dependency

To include Log4j2 in the project, include following maven dependencies.

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

2. Log4j2.xml – Console Logging

You can use below log4j2.xml file logging output into console. Please note that if no configuration file could be located then DefaultConfiguration will be used. This also causes logging output to go to the console.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
	<Appenders>
		<Console name="console" target="SYSTEM_OUT">
			<PatternLayout
				pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Root level="debug" additivity="false">
			<AppenderRef ref="console" />
		</Root>
	</Loggers>
</Configuration>

3. Log4j2.xml – Rolling File Appenders

You can use below log4j2.xml file logging output into date based rolling files – along with console.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
	<Properties>
		<Property name="basePath">C:\\logs</Property>
	</Properties>

	<Appenders>
		<RollingFile name="fileLogger" fileName="${basePath}/app-info.log" filePattern="${basePath}/app-info-%d{yyyy-MM-dd}.log">
			<PatternLayout>
				<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
			</PatternLayout>
			<Policies>
				<TimeBasedTriggeringPolicy interval="1" modulate="true" />
			</Policies>
		</RollingFile>

		<Console name="console" target="SYSTEM_OUT">
			<PatternLayout	pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Logger name="com.howtodoinjava" level="debug" additivity="true">
			<appender-ref ref="fileLogger" level="debug" />
		</Logger>
		<Root level="debug" additivity="false">
			<appender-ref ref="console" />
		</Root>
	</Loggers>
</Configuration>

4. Log4j2.xml – Multile File Appenders

Use this simple log4j2.xml for quick reference to log statements in multiple log files. It logs different level of logs (debug, info etc.) to different files, using LevelRangeFilter, so that your logs are clean and seperated for easy analysis.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">

	<!-- Logging Properties -->
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>
    
    <Appenders>
    
    	<!-- Console Appender -->
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
        
        <!-- File Appenders on need basis -->
        <RollingFile name="frameworkLog" fileName="${APP_LOG_ROOT}/app-framework.log" 
			filePattern="${APP_LOG_ROOT}/app-framework-%d{yyyy-MM-dd}-%i.log">
			<LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="debugLog" fileName="${APP_LOG_ROOT}/app-debug.log" 
			filePattern="${APP_LOG_ROOT}/app-debug-%d{yyyy-MM-dd}-%i.log">
			<LevelRangeFilter minLevel="DEBUG" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="infoLog" fileName="${APP_LOG_ROOT}/app-info.log" 
			filePattern="${APP_LOG_ROOT}/app-info-%d{yyyy-MM-dd}-%i.log" >
			<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="errorLog" fileName="${APP_LOG_ROOT}/app-error.log" 
			filePattern="${APP_LOG_ROOT}/app-error-%d{yyyy-MM-dd}-%i.log" >
			<LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="10"/>
		</RollingFile>
		
		<RollingFile name="perfLog" fileName="${APP_LOG_ROOT}/app-perf.log" 
			filePattern="${APP_LOG_ROOT}/app-perf-%d{yyyy-MM-dd}-%i.log" >
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="1"/>
		</RollingFile>
		
		<RollingFile name="traceLog" fileName="${APP_LOG_ROOT}/app-trace.log" 
			filePattern="${APP_LOG_ROOT}/app-trace-%d{yyyy-MM-dd}-%i.log" >
			<PatternLayout pattern="${LOG_PATTERN}"/>
			<Policies>
				<SizeBasedTriggeringPolicy size="19500KB" />
			</Policies>
			<DefaultRolloverStrategy max="1"/>
		</RollingFile>
		
    </Appenders>

    <Loggers>
    
    	<Logger name="com.howtodoinjava.app.somePackage" additivity="false" level="trace">
    		<AppenderRef ref="traceLog" />
            <AppenderRef ref="Console" />
        </Logger>
        
        <Logger name="com.howtodoinjava.app" additivity="false" level="debug">
	        <AppenderRef ref="debugLog" />
	        <AppenderRef ref="infoLog"  />
            <AppenderRef ref="errorLog" />
            <AppenderRef ref="Console"  />
        </Logger>
        
        <Logger name="org.framework.package" additivity="false" level="info">
            <AppenderRef ref="perfLog" />
            <AppenderRef ref="Console"/>
        </Logger>
                
        <Root level="warn">
            <AppenderRef ref="Console"/>
        </Root>

    </Loggers>

</Configuration>

5. Log4j2.xml File Location

You should put log4j2.xml anywhere in application’s classpath. Log4j will scan all classpath locations to find out this file and then load it.

Log4j2.xml file location
Log4j2.xml file location

6. Demo

Let’s write a java class and write few log statements to verify that logs are appreaing in console and log file as well. It logs different log levels to different logs

package com.howtodoinjava.log4j2.examples;

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

public class Log4j2HelloWorldExample 
{
	private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample.class.getName());
	
	public static void main(String[] args) 
	{
		LOGGER.debug("Debug Message Logged !!!");
		LOGGER.info("Info Message Logged !!!");
		LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError"));
	}
}

Now when you run the above program, you will get below logs in console.

[DEBUG] 2016-06-16 12:17:42.972 [main] Log4j2HelloWorldExample - Debug Message Logged !!!
[INFO ] 2016-06-16 12:17:42.996 [main] Log4j2HelloWorldExample - Info Message Logged !!!
[ERROR] 2016-06-16 12:17:42.997 [main] Log4j2HelloWorldExample - Error Message Logged !!!
java.lang.NullPointerException: NullError
    at com.howtodoinjava.log4j2.examples.Log4j2HelloWorldExample.main(Log4j2HelloWorldExample.java:14) [classes/:?]

If you change the system date and run the application again, you will find two log files in configured location i.e. app-info.log and app-info-2016-06-15.log – where second file is rolled over file.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

11 thoughts on “Log4j2 XML Configuration Example”

  1. Hi,

    How to use different xml file name (mylog4j.xml instead of log4j2.xml) and that should be in different location.

    Reply
  2. i have to read the log4j2.xml which is present in the web-inf folder of my war.Can you please share the code ?Please make sure it uses the latest log4j2.11.1.jar

    Reply
  3. Hello Lokesh,

    I copied exactly the xml file and the java code and run the project on Eclipse using Run-Debug.
    I could see the log lines on the Eclipse console but the file was empty.

    Thank you, Tal

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.