Backend Development 21 min read

Comprehensive Guide to Configuring Log4j2: Dependencies, Configuration Files, PatternLayout, Appenders, Loggers, and Asynchronous Logging

This article provides a detailed tutorial on Log4j2, covering how to add Maven dependencies, write XML configuration files, use PatternLayout placeholders, configure various Appenders and Filters, set up Loggers, enable asynchronous logging, and fine‑tune rolling file policies for Java backend applications.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to Configuring Log4j2: Dependencies, Configuration Files, PatternLayout, Appenders, Loggers, and Asynchronous Logging

1. Adding Dependencies

To use Log4j2 in a Maven project, include the following dependencies:

<!-- Log4j2 API -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.13.3</version>
</dependency>
<!-- Log4j2 Core implementation -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.13.3</version>
</dependency>

For most projects it is recommended to use the log4j-slf4j-impl bridge:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.13.3</version>
</dependency>

2. Configuration File Example

A typical log4j2.xml configuration looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG" monitorInterval="30">
    <!-- Output format -->
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} - [%t] %-5level %logger{36} - %msg%n"/>

    <Appenders>
        <!-- Console output -->
        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <Buffered mode="ONCE" bufferSize="256"/>
        </Console>

        <!-- Rolling file output -->
        <RollingFile name="RollingFile" fileName="/path/to/logs/test.log"
                     filePattern="/path/to/logs/$${date:yyyy-MM}/test-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="10MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
        </Root>
        <Logger name="com.example" level="DEBUG" additivity="false">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
        </Logger>
    </Loggers>
</Configuration>

3. PatternLayout

PatternLayout defines how each log event is formatted. Common placeholders include:

%d : timestamp

%t : thread name

%-5level : log level, left‑aligned to five characters

%logger{36} : logger name (max 36 characters)

%msg : log message

%n : platform‑specific line separator

%M : method name

%L : line number

%l : fully qualified location (class, method, line)

%c : class name

Examples:

<PatternLayout pattern="%d{ISO8601} [%t] %-5level %logger{36} - %msg%n"/>

produces:

2023-08-23T19:34:26,068 [main] INFO  com.zhanfu.Main - This is a Main info message.

Another example with more details:

<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%t] %c{1.} %M [%L] -| %msg%n"/>

produces:

2023-08-23 20:18:06.833 |-INFO  [main] c.z.Main main [11] -| This is a Main info message.

4. Appenders

Appenders define where log events are sent. Common types include:

Console – writes to the console

File – writes to a plain file

RollingFile – writes to a file and rolls over based on time or size

Socket – sends logs to a remote socket server

Kafka – publishes logs to a Kafka topic

Redis – stores logs in Redis

Jdbc – writes logs to a database

For single‑node applications, Console and File are typical; for clustered environments, Socket or Kafka are used for log collection.

5. Console Appender

Key attributes of the <Console> element:

name : identifier of the appender

target : SYSTEM_OUT or SYSTEM_ERR (default SYSTEM_OUT )

follow : whether the console follows log file rotation (default false )

immediateFlush : flush after each write (default true )

Typical child elements:

<PatternLayout> – custom format

<ThresholdFilter> – level‑based filtering

<RegexFilter> – regex‑based filtering

5.1 Filter Example

<Console name="console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    <ThresholdFilter level="WARN" onMatch="NEUTRAL" onMismatch="DENY"/>
    <RegexFilter regex=".*\[(main|AsyncLogger)\].*"/>
</Console>

This configuration accepts logs at WARN level or higher, then applies the regex filter; lower‑level logs are denied.

6. RollingFile Appender

RollingFile writes logs to a file and creates archived files when a trigger condition is met (time or size). Example configuration:

<Appenders>
    <RollingFile name="RollingFile" fileName="/logs/app.log"
                 filePattern="logs/app-%d{yyyy-MM-dd-HH}-%i.log">
        <PatternLayout>
            <pattern>%d %p %c{1.} [%t] %m%n</pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            <SizeBasedTriggeringPolicy size="10 MB"/>
        </Policies>
        <DefaultRolloverStrategy max="5"/>
    </RollingFile>
</Appenders>

The filePattern can contain placeholders such as %d (date), %i (index), %n (line separator) and %m (file name). Example output filenames:

app-2021-08-30-15-1.log app-2021-08-30-15-2.log app-2021-08-30-15-3.log

6.1 Policies

TimeBasedTriggeringPolicy rolls over after a specified time interval. Attributes:

interval : time interval (e.g., 1 hour when using %d{yyyy-MM-dd-HH} )

modulate : if true , alignment starts at the nearest boundary (e.g., 00:00)

SizeBasedTriggeringPolicy rolls over when the file reaches a given size (default 10 MB).

6.2 DefaultRolloverStrategy

Controls how many rolled files are kept and how they are deleted. Important attributes:

max : maximum number of files (default 7)

min : minimum number of files (default 1)

fileIndex : naming scheme (default %s )

compressionLevel : zip compression level (default 6)

It also supports child elements such as <Delete> and <CustomDelete> for age‑based cleanup.

7. Loggers

Loggers define the logging behavior for specific packages or classes. Important attributes:

name : logger name (e.g., package or class name)

level : log level for this logger

additivity : whether to inherit appenders from parent loggers

includeLocation : include source location information

suppressExceptions : hide exception stack traces

Example:

<Loggers>
    <Logger name="com.example.MyLogger" level="info">
        <AppenderRef ref="MyAppender"/>
    </Logger>
    <Root level="error">
        <AppenderRef ref="Console"/>
    </Root>
</Loggers>

8. Asynchronous Logging

Log4j2 can write logs asynchronously for higher throughput. Basic async configuration:

<Configuration status="WARN">
    <Appenders>
        <File name="File" fileName="logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
            </PatternLayout>
        </File>
        <Async name="Async">
            <AppenderRef ref="File"/>
        </Async>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Async"/>
        </Root>
    </Loggers>
</Configuration>

A simple benchmark shows that the async setup dramatically reduces total logging time compared with the synchronous version.

Log4j2 supports four blocking queue implementations for async logging; one can be selected explicitly, for example:

<Configuration name="LinkedTransferQueueExample">
    <Appenders>
        <List name="List"/>
        <Async name="Async" bufferSize="262144">
            <AppenderRef ref="List"/>
            <AsyncQueueFullPolicy type="Discard"/>
            <LinkedTransferQueue/>
        </Async>
    </Appenders>
    <Loggers>
        <Root>
            <AppenderRef ref="Async"/>
        </Root>
    </Loggers>
</Configuration>

If the DisruptorBlockingQueue is desired, the additional disruptor dependency (e.g., version 3.4.0 for Log4j 2.17.1) must be added.

Conclusion

This tutorial has covered the most common Log4j2 configuration aspects, from Maven dependencies to advanced asynchronous logging and rolling file strategies. Although it does not delve into the internal implementation details, the examples should enable newcomers to set up Log4j2 for a wide range of backend Java applications.

For further reading, refer to the official Log4j2 manual: https://logging.apache.org/log4j/2.x/manual/

Configurationlog4j2Java LoggingRollingFileAsync loggingPatternLayout
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.