Log4j2

Language: Java

CLI/Utils

Log4j2 was created by the Apache Software Foundation to address performance and flexibility limitations in Log4j 1.x. It leverages a plugin architecture, supports various appenders and layouts, and provides better performance through asynchronous logging and garbage-free design.

Log4j2 is a high-performance, flexible, and reliable logging framework for Java applications. It is the successor to Log4j and provides advanced features such as asynchronous logging, custom log levels, and plugin support.

Installation

maven: Add org.apache.logging.log4j:log4j-core and org.apache.logging.log4j:log4j-api dependencies in pom.xml
gradle: Add implementation 'org.apache.logging.log4j:log4j-api:2.20.0' and implementation 'org.apache.logging.log4j:log4j-core:2.20.0' in build.gradle

Usage

Log4j2 allows developers to log messages at different levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL). It supports configuration through XML, JSON, YAML, or properties files and integrates with SLF4J for logging abstraction.

Creating a logger

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

public class MyApp {
    private static final Logger logger = LogManager.getLogger(MyApp.class);

    public static void main(String[] args) {
        logger.info("Application started");
    }
}

Initializes a Log4j2 logger and logs an INFO level message.

Logging with parameters

String user = "Alice";
logger.debug("User {} has logged in", user);

Shows parameterized logging to avoid string concatenation overhead.

Logging exceptions

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    logger.error("An error occurred: {}", e.getMessage(), e);
}

Logs an exception with a message and stack trace.

Asynchronous logging

<Configuration status="WARN">
  <Appenders>
    <Async name="AsyncConsole">
      <Console />
    </Async>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="AsyncConsole" />
    </Root>
  </Loggers>
</Configuration>

Demonstrates asynchronous logging configuration for better performance.

Custom log levels and appenders

<Logger name="com.example" level="debug" additivity="false">
  <AppenderRef ref="FileAppender" />
</Logger>

Defines a logger with a specific level and appender for fine-grained control.

Using SLF4J with Log4j2

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Logger logger = LoggerFactory.getLogger(MyApp.class);
logger.info("Message through SLF4J facade");

Integrates Log4j2 with SLF4J for logging abstraction.

Error Handling

NoClassDefFoundError for LogManager or Logger: Ensure both log4j-api and log4j-core are present in the classpath.
StatusLogger warnings: Check configuration file format and location; Log4j2 may fallback to default configuration if it cannot find the custom config.

Best Practices

Use asynchronous logging for high-throughput applications.

Externalize configuration in XML, JSON, YAML, or properties files for flexibility.

Use parameterized logging instead of string concatenation for performance.

Organize loggers per package or class for clarity.

Leverage multiple appenders (console, file, rolling file, etc.) for different logging needs.