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.
1. log4j2 maven dependency
To include Log4j2 in your project, include below maven dependency in your project.
<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 for logging into Console
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 for logging into rolling files
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 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.

5. log4j2.xml example
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.
6. log4j2.xml with 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>
Happy Learning !!
nha
For bullet #2 above, is the root level set to “debug” by default? I want it to be “INFO”, how can I accomplish this?
Nageswarareddy Chaduvula
Hi,
How to use different xml file name (mylog4j.xml instead of log4j2.xml) and that should be in different location.
Lokesh Gupta
Use framework specific overrides. For example, in spring boot, use property override in
application.properties.
shaleen
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
Ivan
Is there some examples that explain how rotate stdout and stderr?
Thanks.
Ravi
How to read the configuration file from a directory(C:\config)?
Hien Khuu
how to log into console with json format?
Tal
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
brahim
<Logger name="com.howtodoinjava"
In the logger name, replace "com.howtodoinjava" by the package of your class.
Samuel
After changing the package “com.howtodoinjava” to mine I am still getting the log messages to display only on the console and not on the file.
Abhishek Chauhan
Yes same happened to me . I got console messages but didn’t get file either by .properties file or .xml file