Log4j2 Tutorial

Apache Log4j2 is an upgrade to Log4j 1.x that provides significant improvements over its predecessor. This page list down various hello world configuration examples and useful tutorials for working with Log4j2.

1. Log4j2 Maven Dependencies

To include Log4j2, include below maven dependencies.

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

Gradle dependecies are:

implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.14.1'
implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.14.1'

2. Log4j2 XML Configuration Example

A sample log4j2.xml configuration file for reference.

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

3. Log4j2 Properties Configuration Example

A sample log4j2.properties file for reference.

status = warn
name = PropertiesConfig
 
#Make sure to change the log file path as per your need
property.filename = C:\\logs\\debug.log
 
filters = threshold
 
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console
 
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
appenders = rolling
 
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
 
loggers = console, rolling
 
#Make sure to change the package structure as per your application
 
logger.rolling.name = com.howtodoinjava
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile

4. Log4j2 Examples

  1. Log4j2 ConsoleAppender Example
  2. Log4j2 RollingFileAppender example
  3. Log4j2 LevelRangeFilter Example
  4. Log4j2 Multiple appenders example
  5. Log4j2 HTMLLayout Configuration Example
  6. Log4j2 ThreadContext – Fish Tagging Logs of Same Transaction
  7. Log4j2 – Useful Conversion Pattern Examples
  8. Configure Log4j2 for JUnit Testcases
  9. Log4j2 JSON Configuration Example
  10. Log4j2 Properties File Example
  11. Log4j2 XML Configuration Example

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.

HowToDoInJava

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