In this tutorial, we will get to know Log4j 2. An essential component of software development is event logging. Although there are many frameworks in the Java environment, Log4J has been the most well-liked for decades because of its simplicity and flexibility.
Table of Contents
What is Log4j 2?
Apache Log4j is a Java-based logging utility. Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback’s architecture.
Apache Log4j2 versions 2.0-beta7 through 2.17.0 (excluding security fix releases 2.3.2 and 2.12.4) are vulnerable to a remote code execution (RCE) attack where an attacker with permission to modify the logging configuration file can construct a malicious configuration using a JDBC Appender with a data source referencing a JNDI URI which can execute remote code. This issue is fixed by limiting JNDI data source names to the java protocol in Log4j2 versions 2.17.1, 2.12.4, and 2.3.2.
Log4j Components
Log4j Loggers
Loggers provide a way to organize log messages based on their severity and purpose, making it easier to diagnose and troubleshoot issues in your code.
Types of Loggers in Log4j
There are two types of loggers in Log4j: root loggers and named loggers.
- Root Logger: The root logger is the top-level logger in the Log4j hierarchy and is responsible for capturing all log messages in the application. By default, the root logger has a log level of DEBUG and sends log messages to the console appender.
- Named Loggers: Named loggers are loggers that have been given a specific name and are used to log messages for specific parts of the application. You can create them for specific packages, classes, or even individual methods. They can have a different log level and appender than the root logger, making it possible to customize the logging for specific parts of
Log4j level
Primarily, there are five kinds of log levels
1. TRACE: The TRACE level is the lowest level of severity. You can use it for detailed log messages that are primarily useful for debugging purposes.
2. DEBUG: We use the DEBUG level for messages that provide detailed information about the application’s execution. We usually use these messages to help diagnose issues and problems.
3. INFO: The INFO level is used for messages that provide general information about the application’s progress. These messages are used to give an overview of what the application is doing.
4. WARN: The WARN level is used for messages that indicate a potential problem or issue with the application. These messages are used to alert developers to potential issues that need to be addressed.
5. ERROR: The ERROR level is used to indicate errors that might still allow the application to run.
6. FATAL: The FATAL level is the highest level of severity and is used for messages that indicate a critical failure in the application. These messages are used to alert developers to issues that have caused the application to stop functioning.
7. OFF: No logging
Appenders
It is used to deliver LogEvents to their destination. It decides what will happen with log information. In simple words, it is used to write the logs in a file. Following are a few types of Appenders.
1. File Appender: It writes log messages to a specified file.
2. Console Appender: Writes log messages to the console.
3. Rolling File Appender: They write log messages to a file and automatically roll over to a new file when the current file reaches a specified size.
4. Daily Rolling File Appender: Writes log messages to a file and automatically rolls over to a new file at a specified time interval.
5. JDBC Appender: It writes log messages to a database using JDBC.
6. SMTP Appender: Writes log messages to an email using SMTP.
Layouts
In Log4j, we use a layout to format log messages before they are written to an appender. There are several different types of layouts available in Log4j, each with its own strengths and weaknesses. The different types of Log4j layouts include:
- SimpleLayout
- HTMLLayout
- PatternLayout
- XMLLayout
Add Log4j Dependency
Add log4j dependency to the Java project.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>3.0.0-alpha1</version>
</dependency>
Let us create a simple program.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log_Demo {
// Creating a logger
private static Logger logger = LogManager.getLogger();
// Log messages
public static void main(String[] args) {
logger.debug("It is a debug logger.");
logger.error("It is an error logger.");
logger.fatal("It is a fatal logger.");
logger.info("It is a info logger.");
logger.trace("It is a trace logger.");
logger.warn("It is a warn logger.");
}
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2023/09/image-114.png?w=644)
We can observe that I have created a Logger using LogManager and explicitly using all the levels with a string message. We have used all the levels but in the console, we are seeing only two levels. Actually when we do not provide any configuration file(yet to be covered), by default Log4j uses a default configuration.
The default configuration, provided in the DefaultConfiguration class, will set up:
- A ConsoleAppender attached to the root logger i.e. logs will be printed on the console.
- A PatternLayout set to the pattern “%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} – %msg%n” attached to the ConsoleAppender
Note that by default Log4j assigns the root logger to Level.ERROR and those logs will be printed on the standard console.