Log4j (short for Logging for Java) is a reliable, fast, and flexible logging framework developed by the Apache Software Foundation. It allows developers to log messages according to different severity levels and send those messages to multiple destinations like the console, files, GUI components, databases, or remote servers.
Evolution:
- Log4j 1.x: Original version, now deprecated.
- Log4j 2.x: Modern, feature-rich, secure version with asynchronous capabilities.
- Log4j 3 (Upcoming): Under development to build on Log4j 2.
Log4j Architecture
The architecture of Log4j is based on the following key components:
1. Logger
The Logger is responsible for capturing log messages from the application code. Each Logger is typically named based on the class or package in which it is used.
2. Appender
Appenders define where the log messages go. Common appenders include:
ConsoleAppender
FileAppender
RollingFileAppender
JDBCAppender
SocketAppender
3. Layout
Layouts define how the log messages are formatted. They convert a log event into a readable string. Layout types include:
PatternLayout
JSONLayout
XMLLayout
HTMLLayout
4. Filter
Filters decide whether a particular log event should be logged or not based on conditions like log level, message content, or context.
Logging Levels in Log4j
Log4j supports a standard set of logging levels:

Configuration Methods
Log4j can be configured in multiple ways:
1. Programmatic Configuration
You can configure Log4j directly in your Java code. This is useful for small applications or where dynamic configuration is needed.
2. Configuration Files
Log4j supports external configuration via:
log4j2.xml
log4j2.json
log4j2.yaml
log4j2.properties
- These files make it easy to manage logging behavior without recompiling the code.
Simple Example Using XML Configuration
Step 1: Create log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Code language: HTML, XML (xml)
Step 2: Java Code
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."); logger.warn("Potential issue detected."); logger.error("Something went wrong!"); } }
Problem Statement:
LotusJavaPrince and Mahesh are building a banking application. They want detailed logging for different modules such as Authentication
, Loan Processing
, and Transaction Management
. Logs should go to a file with daily rolling, and different log levels must be used for different modules.
log4j2.xml Configuration:
<Configuration status="INFO">
<Appenders>
<RollingFile name="FileAppender" fileName="logs/bank.log"
filePattern="logs/bank-%d{yyyy-MM-dd}.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.bank.auth" level="DEBUG" additivity="false">
<AppenderRef ref="FileAppender"/>
</Logger>
<Logger name="com.bank.transaction" level="INFO" additivity="false">
<AppenderRef ref="FileAppender"/>
</Logger>
<Logger name="com.bank.loan" level="ERROR" additivity="false">
<AppenderRef ref="FileAppender"/>
</Logger>
<Root level="WARN">
<AppenderRef ref="FileAppender"/>
</Root>
</Loggers>
</Configuration>
Code language: HTML, XML (xml)
Java Code
package com.bank.auth; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class LoginService { private static final Logger logger = LogManager.getLogger(LoginService.class); public void authenticate(String username) { logger.debug("Authenticating user: " + username); // Simulate login logic if (username.equals("admin")) { logger.info("Admin logged in successfully."); } else { logger.warn("Unrecognized user tried to log in: " + username); } } }
Log4j is a robust and industry-standard logging framework that enables Java developers to implement logging that is scalable, readable, and easy to manage. Whether you’re developing a small desktop app or a large-scale enterprise system, Log4j’s capabilities ensure effective monitoring and troubleshooting of your application.
It supports a wide range of configurations, multiple output formats, and provides superior performance compared to Java’s built-in logging framework. Understanding and using Log4j is a best practice in enterprise Java development.