Comprehensive Guide to Apache Log4j2: Features, Performance, Configuration, and Usage

This article provides an in‑depth overview of Apache Log4j2, comparing it with Logback and Log4j 1, highlighting its superior asynchronous performance, zero‑GC operation, flexible configuration formats, rich appender ecosystem, and practical code examples for Maven integration, XML setup, and advanced logging techniques.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Comprehensive Guide to Apache Log4j2: Features, Performance, Configuration, and Usage

Log4j2 Overview

Log4j2 is the modern successor to Logback and Log4j 1, offering dramatically improved asynchronous performance, simplified configuration, and powerful parameter formatting.

Key Advantages

Simplified configuration (XML, JSON, YML, Properties)

Advanced parameter formatting using {} placeholders and String.format style

Exceptional asynchronous performance (up to ten times faster than Logback in benchmarks)

Zero‑GC mode since version 2.6, reusing message objects to avoid allocations

High‑performance I/O via MemoryMappedFileAppender Rich appender support (JMS, JPA, Kafka, HTTP, MongoDB, etc.)

Modules

Log4j2 consists of two modules: log4j-api (the façade) and log4j-core (the implementation).

Basic Usage

Include the core dependency in Maven:

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

Create a logger:

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

Logger logger = LogManager.getLogger(MyClass.class);
logger.error(...);
logger.warn(...);
logger.info(...);
logger.debug(...);
logger.trace(...);

Configuration Example (log4j2.xml)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration name="XInclude" status="warn">
  <Properties>
    <Property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%t] %-40.40c{1.} : %m%n"/>
  </Properties>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="${PATTERN}"/>
    </Console>
    <RollingFile name="File" fileName="logs/app.log" filePattern="logs/archives/app-%d{yyyy-MM-dd}-%i.log.gz">
      <PatternLayout pattern="${PATTERN}"/>
      <Policies>
        <TimeBasedTriggeringPolicy/>
        <SizeBasedTriggeringPolicy size="1 GB"/>
      </Policies>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="INFO">
      <AppenderRef ref="Console"/>
      <AppenderRef ref="File"/>
    </Root>
  </Loggers>
</Configuration>

Advanced Features

Lazy logging with lambda suppliers reduces unnecessary object creation:

logger.debug("Request payload: {}", () -> JSON.toJSONString(requestDto));

Full asynchronous mode can be enabled via JVM argument:

-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

Conclusion

Log4j2 currently offers the best performance and feature set among Java logging frameworks, making it the recommended choice for new projects and a strong candidate for replacing older loggers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaperformancelogginglog4j2
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

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.