- log4j - Home
- log4j - Overview
- log4j - Installation
- log4j - Architecture
- log4j - Configuration
- log4j - Sample Program
- log4j - Logging Methods
- log4j - Logging Levels
- log4j - ConsoleAppender
- log4j - Logging in Database
Log4j - Formatting Layouts
- log4j - Log Formatting
- log4j - CSV Parameter Layout
- log4j - CSV Log Event Layout
- log4j - HTML Layout
- log4j - Pattern Layout
- log4j - Json Template Layout
Log4j - File Appenders
- log4j - Logging in Files
- log4j - FileAppender
- log4j - Separate Folder per Month
- log4j - Daily log File Generation
log4j Resources
log4j - Quick Guide
log4j - Overview
log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License.
log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.
log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog, etc.
log4j has three main components:
loggers: Responsible for capturing logging information.
appenders: Responsible for publishing logging information to various preferred destinations.
layouts: Responsible for formatting logging information in different styles.
History of log4j
Started in early 1996 as tracing API for the E.U. SEMPER (Secure Electronic Marketplace for Europe) project.
After countless enhancements and several incarnations, the initial API has evolved to become log4j, a popular logging package for Java.
The package is distributed under the Apache Software License, a full-fledged open source license certified by the open source initiative.
The latest log4j version, including its full-source code, class files, and documentation can be found at https://logging.apache.org/log4j/2.x/download.html.
log4j Features
It is thread-safe.
It is optimized for speed.
It is based on a named logger hierarchy.
It supports multiple output appenders per logger.
It supports internationalization.
It is not restricted to a predefined set of facilities.
Logging behavior can be set at runtime using a configuration file.
It is designed to handle Java Exceptions from the start.
It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
The format of the log output can be easily changed by extending the Layout class.
The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.
Pros and Cons of Logging
Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application's runtime information.
Logging does have its drawbacks also. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible.
Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.
log4j - Installation
log4j API package is distributed under the Apache Software License, a full-fledged open source license certified by the open source initiative.
The latest log4j version, including full-source code, class files and documentation can be found at https://logging.apache.org/log4j/2.x/download.html.
To install log4j on your system, download apache-log4j-2.25.1-bin.zip from the specified URL and follow the steps give below.
Step 1
Unzip the downloaded file in D:\Projects\apache-log4j-2.25.1-bin directory.
Step 2
This step is optional and depends on what features you are going to use from log4j framework. If you already have following packages installed on your machine then it is fine, otherwise you need to install them to make log4j work.
JavaMail API: The e-mail based logging feature in log4j requires the Java Mail API (mail.jar) to be installed on your machine from https://glassfish.org/.
JavaBeans Activation Framework: The Java Mail API will also require that the JavaBeans Activation Framework (activation.jar) be installed on your machine from https://www.oracle.com/java/technologies/?er=221886.
Java Message Service: The JMS-compatible features of log4j will require that both JMS and Java Naming and Directory Interface JNDI be installed on your machine from https://www.oracle.com/java/technologies/?er=221886.
XML Parser: You need a JAXP-compatible XML parser to use log4j. Make sure you have Xerces.jar installed on your machine from http://xerces.apache.org/xerces-j/install.html.
Set CLASSPATH Variable
Set the CLASSPATH environment variable to point to the log4j jar location. Assuming, you have stored log4j and related jars in Projects folder on various Operating Systems as follows.
| OS | Output |
|---|---|
| Windows | Set the environment variable CLASSPATH to %CLASSPATH%;D:\Projects\apache-log4j-2.25.1-bin\log4j-core-2.25.1.jar;D:\Projects\apache-log4j-2.25.1-bin\log4j-api-2.25.1.jar;D:\Projects\apache-log4j-2.25.1-bin\log4j-layout-template-json-2.25.1.jar; |
| Linux | export CLASSPATH=$CLASSPATH:Projects/apache-log4j-2.25.1-bin/log4j-core-2.25.1.jar:Projects/apache-log4j-2.25.1-bin/log4j-api-2.25.1.jar:Projects/apache-log4j-2.25.1-bin/log4j-layout-template-json-2.25.1.jar:. |
| Mac | export CLASSPATH=$CLASSPATH:Projects/apache-log4j-2.25.1-bin/log4j-core-2.25.1.jar:Projects/apache-log4j-2.25.1-bin/log4j-api-2.25.1.jar:Projects/apache-log4j-2.25.1-bin/log4j-layout-template-json-2.25.1.jar:. |
log4j - Architecture
log4j API follows a layered architecture where each layer provides different objects to perform different tasks. This layered architecture makes the design flexible and easy to extend in future.
There are two types of objects available with log4j framework.
Core Objects: These are mandatory objects of the framework. They are required to use the framework.
Support Objects: These are optional objects of the framework. They support core objects to perform additional but important tasks.
Core Objects
Core objects include the following types of objects â
Logger Object
The top-level layer is the Logger which provides the Logger object. The Logger object is responsible for capturing logging information and they are stored in a namespace hierarchy.
Layout Object
The layout layer provides objects which are used to format logging information in different styles. It provides support to appender objects before publishing logging information.
Layout objects play an important role in publishing logging information in a way that is human-readable and reusable.
Appender Object
This is a lower-level layer which provides Appender objects. The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, console, UNIX Syslog, etc.
The following virtual diagram shows the components of a log4J framework:
Support Objects
There are other important objects in the log4j framework that play a vital role in the logging framework:
Level Object
The Level object defines the granularity and priority of any logging information. There are seven levels of logging defined within the API: OFF, DEBUG, INFO, ERROR, WARN, FATAL, and ALL.
Filter Object
The Filter object is used to analyze logging information and make further decisions on whether that information should be logged or not.
An Appender objects can have several Filter objects associated with them. If logging information is passed to a particular Appender object, all the Filter objects associated with that Appender need to approve the logging information before it can be published to the attached destination.
ObjectRenderer
The ObjectRenderer object is specialized in providing a String representation of different objects passed to the logging framework. This object is used by Layout objects to prepare the final logging information.
LogManager
The LogManager object manages the logging framework. It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class.
log4j - Configuration
The previous chapter explained the core components of log4j. This chapter explains how you can configure the core components using a configuration file. Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file.
The log4j2.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j2.properties in the CLASSPATH.
The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it.
Set the appender named X to be a valid appender.
Set the layout for the appender X.
log4j.properties Syntax:
Following is the syntax of log4j.properties file for an appender X:
# Define a console appender named X appender.0.type = Console appender.0.name = X appender.0.layout.type = PatternLayout appender.0.layout.pattern = %p - %m%n # Define the root logger with appender X rootLogger.level = INFO rootLogger.appenderRef.0.ref = X rootLogger.appenderRef.0.level = WARN
log4j.properties Example
Using the above syntax, we define the following in log4j.properties file:
The level of the root logger is defined as DEBUG, The DEBUG appender named MAIN to it.
The appender MAIN is defined with type File. It writes to a file named main.log located in the logs directory.
The layout pattern defined is %p - %m%n, which means the printed logging message will be followed by a newline character.
# Define the file appender appender.0.type = File appender.0.name = MAIN appender.0.fileName = logs/main.log appender.0.layout.type = PatternLayout appender.0.layout.pattern = %p - %m%n # Define the root logger with appender file rootLogger.level = INFO rootLogger.appenderRef.0.ref = MAIN rootLogger.appenderRef.0.level = DEBUG
It is important to note that log4j supports UNIX-style variable substitution such as ${variableName}.
Debug Level
We have used DEBUG with both the appenders. All the possible options are:
- TRACE
- DEBUG
- INFO
- WARN
- ERROR
- FATAL
- ALL
These levels are explained later in this tutorial.
Appenders
Apache log4j provides Appender objects which are primarily responsible for printing logging messages to different destinations such as consoles, files, sockets, NT event logs, etc.
Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.
| Property | Description |
|---|---|
| layout | Appender uses the Layout objects and the conversion pattern associated with them to format the logging information. |
| target | The target may be a console, a file, or another item depending on the appender. |
| level | The level is required to control the filtration of the log messages. |
| threshold | Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level. |
| filter | The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored. |
We can add an Appender object to a Logger by including the following setting in the configuration file with the following method:
log4j.logger.[logger-name]=level, appender1,appender..n
You can write same configuration in XML format as follows:
<logger name="com.apress.logging.log4j" additivity="false"> <appender-ref ref="appender1"/> <appender-ref ref="appender2"/> </logger>
If you are willing to add Appender object inside your program then you can use following method:
public void addAppender(Appender appender);
The addAppender() method adds an Appender to the Logger object. As the example configuration demonstrates, it is possible to add many Appender objects to a logger in a comma-separated list, each printing logging information to separate destinations.
We have used only one appender FileAppender in our example above. All the possible appender options are:
AppenderSkeleton
AsyncAppender
ConsoleAppender
DailyRollingFileAppender
ExternallyRolledFileAppender
FileAppender
JDBCAppender
JMSAppender
LF5Appender
NTEventLogAppender
NullAppender
RollingFileAppender
SMTPAppender
SocketAppender
SocketHubAppender
SyslogAppender
TelnetAppender
WriterAppender
We would cover FileAppender in Logging in Files and JDBC Appender would be covered in Logging in Database.
Layout
We have used PatternLayout with our appender. All the possible options are:
JsonTemplateLayout
DateLayout
HTMLLayout
PatternLayout
SimpleLayout
XMLLayout
Using HTMLLayout and XMLLayout, you can generate log in HTML and in XML format as well.
Layout Formatting
You would learn how to format a log message in chapter: Log Formatting.
log4j - Sample Program
We have seen how to create a configuration file in log4j - Configuration. This chapter describe how to generate debug messages and log them in a simple text file.
Following is a simple configuration file created for our example. Let us revise it once again:
The appender CONSOLE is defined with type Console and writes to console.
The layout pattern defined is %p - %m%n, which means the printed logging message will be followed by a newline character.
The appender MAIN is defined with type File and writes to a file named main.log located in the logs directory.
The layout type defined is JsonTemplateLayout, which means the printed logging message will be in JSON format.
The level of the root logger is defined as DEBUG and attaches appenders named CONSOLE and MAIN with corresponding levels to it.
The contents of log4j2.properties file are as follows −
log4j2.properties
appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = PatternLayout appender.0.layout.pattern = %p - %m%n appender.1.type = File appender.1.name = MAIN appender.1.fileName = logs/main.log appender.1.layout.type = JsonTemplateLayout rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE rootLogger.appenderRef.0.level = WARN rootLogger.appenderRef.1.ref = MAIN rootLogger.appenderRef.0.level = INFO
Using log4j in Java Program
The following Java class is a very simple example that initializes, and then uses, the log4j logging library for Java applications.
Log4jDemo.java
package com.tutorialspoint;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name by default to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args)throws IOException,SQLException{
LOGGER.info("Hello this is a info message");
LOGGER.debug("Hello this is an debug message");
LOGGER.warn("Hello this is a warning message");
}
}
Compile and Execute
Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
All the libraries should be available in CLASSPATH and your log4j2.properties file should be available in PATH. Follow the steps give below −
Create log4j2.properties as shown above.
Create Log4jDemo.java as shown above and compile it.
Execute Log4jDemo binary to run the program.
Output
You would get the following result inside logs/main.log file −
{"@timestamp":"2025-09-04T10:36:40.322Z","ecs.version":"1.2.0","log.level":"INFO","message":"Hello this is a info message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
{"@timestamp":"2025-09-04T10:36:40.325Z","ecs.version":"1.2.0","log.level":"DEBUG","message":"Hello this is an debug message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
{"@timestamp":"2025-09-04T10:36:40.325Z","ecs.version":"1.2.0","log.level":"WARN","message":"Hello this is a warning message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
And following message will be printed on console −
INFO - Hello this is a info message WARN - Hello this is a warning message
log4j - Logging Methods
Logger class provides a variety of methods to handle logging activities. The Logger class does not allow us to instantiate a new Logger instance but we can use LogManager which provides many static methods for obtaining a Logger object, like following −
- public static Logger getRootLogger();
- public static Logger getLogger(String name);
The first of the two methods returns the application instance's root logger and it does not have a name.
Any other named Logger object instance is obtained through the second method by passing the name of the logger. The name of the logger can be any string you can pass, usually a class or a package name as we have used in the last chapter and it is mentioned below −
static Logger log = LogManager.getLogger(log4jDemo.class.getName());
Logging Methods
Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.
| # | Methods and Description |
|---|---|
| 1 |
public void debug(Object message)
It prints messages with the level Level.DEBUG. |
| 2 |
public void error(Object message)
It prints messages with the level Level.ERROR. |
| 3 |
public void fatal(Object message)
It prints messages with the level Level.FATAL. |
| 4 |
public void info(Object message)
It prints messages with the level Level.INFO. |
| 5 |
public void warn(Object message)
It prints messages with the level Level.WARN. |
| 6 |
public void trace(Object message)
It prints messages with the level Level.TRACE. |
Example - Usage of Log Levels
All the levels are defined in the org.apache.logging.log4j.Level class and any of the above mentioned methods can be called as follows −
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args){
LOGGER.trace("Trace Message!");
LOGGER.debug("Debug Message!");
LOGGER.info("Info Message!");
LOGGER.warn("Warn Message!");
LOGGER.error("Error Message!");
LOGGER.fatal("Fatal Message!");
}
}
Update the log4j2.properties to use the Console Appender.
Log4j2.properties
appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = PatternLayout appender.0.layout.pattern = %p - %m%n rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
Output
When you compile and run Log4jDemo program, it would generate the following result −
DEBUG - Debug Message! INFO - Info Message! WARN - Warn Message! ERROR - Error Message! FATAL - Fatal Message!
All the debug messages make more sense when they are used in combination with levels. We will cover levels in the next chapter and then, you would have a good understanding of how to use these methods in combination with different levels of debugging.
log4j - Logging Levels
The org.apache.logging.log4j.Level levels. You can also define your custom levels by sub-classing the Level class.
| Level | Description |
|---|---|
| ALL | All levels including custom levels. |
| DEBUG | Designates fine-grained informational events that are most useful to debug an application. |
| INFO | Designates informational messages that highlight the progress of the application at coarse-grained level. |
| WARN | Designates potentially harmful situations. |
| ERROR | Designates error events that might still allow the application to continue running. |
| FATAL | Designates very severe error events that will presumably lead the application to abort. |
| OFF | The highest possible rank and is intended to turn off logging. |
| TRACE | Designates finer-grained informational events than the DEBUG. |
How do Levels Works?
A log request of level p in a logger with level q is enabled if p >= q. This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
Example - Filtering Messages using LOG Level
The Following example shows how we can filter all our DEBUG and INFO messages. This program uses of logger method setLevel(Level.X) to set a desired logging level:
This example would print all the messages except Debug and Info:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.atLevel(Level.WARN);
LOGGER.trace("Trace Message!");
LOGGER.debug("Debug Message!");
LOGGER.info("Info Message!");
LOGGER.warn("Warn Message!");
LOGGER.error("Error Message!");
LOGGER.fatal("Fatal Message!");
}
}
Output
When you compile and run the LogClass program, it would generate the following result −
2025-09-04T13:41:43.223410900Z main ERROR Error Message! 2025-09-04T13:41:43.227410200Z main FATAL Fatal Message!
Example - Setting Levels using Configuration File
log4j provides you configuration file based level setting which sets you free from changing the source code when you want to change the debugging level.
Following is an example configuration file which would perform the same task as we did using the log.setLevel(Level.WARN) method in the above example.
Log4j2.properties
appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = PatternLayout appender.0.layout.pattern = %p - %m%n rootLogger.level = WARN rootLogger.appenderRef.0.ref = CONSOLE
Let us now use our following program −
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.trace("Trace Message!");
LOGGER.debug("Debug Message!");
LOGGER.info("Info Message!");
LOGGER.warn("Warn Message!");
LOGGER.error("Error Message!");
LOGGER.fatal("Fatal Message!");
}
}
Output
Now compile and run the above program and you would get following result in console −
WARN - Warn Message! ERROR - Error Message! FATAL - Fatal Message!
log4j - ConsoleAppender
There may be a requirement to generate your on console as well along with log files which makes debugging easier during development phases.
To write your logging information on console, you would have to use org.apache.logging.log4j.ConsoleAppender class
log4j2.properties
appender.0.type = Console appender.0.name = logFile
log4j2.xml
<Appenders>
<Console name="logFile">
<PatternLayout pattern="%d [%t] %p %c - %m%n"/>
</Appenders>
ConsoleAppender Configuration
ConsoleAppender has the following configurable parameters:
| Property | Type | Default Value | Description |
|---|---|---|---|
| name | String | The name of the appender. | |
| bufferSize | int | 8192 | The size of the ByteBuffer internally used by the appender. |
| direct | boolean | false | If set to true, log events will be written directly to either FileDescriptor.out or FileDescriptor.err. This setting bypasses the buffering of System.out and System.err and might provide a performance comparable to a file appender. This setting is incompatible with the follow attribute. |
| follow | boolean | false | If set to true, the appender will honor reassignments of System.out (resp. System.err) via System.setOut (resp. System.setErr). Otherwise, the value of System.out (resp. System.err) at configuration time will be used. This setting is incompatible with the direct attribute. |
| ignoreExceptions | boolean | true | If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored. |
| immediateFlush | boolean | true | If set to true, the appender will flush its internal buffer after each event. |
| target | Target | SYSTEM_OUT | It specifies which standard output stream to use: SYSTEM_OUT - It uses the standard output. SYSTEM_ERR - It uses the standard error output. |
| filter | String | Allows filtering log events just before they are formatted and sent. | |
| layout | Layout | Formats log events. |
ConsoleAppender Configuration Examples
Following is a sample configuration file log4j2.properties for ConsoleAppender −
log4j2.properties
# Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = PatternLayout appender.0.layout.pattern = %d [%t] %p %c - %m%n # Define the root logger with appender console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content:
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
<Appenders>
<Console name="CONSOLE">
<PatternLayout pattern="%d [%t] %p %c - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>
Example - Usage of ConsoleAppender
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
We're using log4j2.properties file.
Output
Compile and run the above program. It would print the following log information on the console:
2025-09-07 12:10:28,511 [main] DEBUG com.tutorialspoint.Log4jDemo - Hello this is an debug message 2025-09-07 12:10:28,517 [main] INFO com.tutorialspoint.Log4jDemo - Hello this is an info message
log4j - Logging in Database
The log4j API provides the org.apache.logging.log4j.jdbc.JDBCAppender object, which can put logging information in a specified database.
log4j2.properties
appender.0.type = JDBC appender.0.name = JDBC appender.0.tableName = logs
log4j2.xml
<appenders>
<Jdbc name="databaseAppender" tableName="logs">
<DriverManager url="jdbc:mysql://localhost:3306/tutorials" username="guest" password="guest123" />
<Column name="level" pattern="%level" />
<Column name="logger" pattern="%logger" />
<Column name="message" pattern="%message" />
</Jdbc>
</appenders>
JDBCAppender Configuration
JDBCAppender has the following configurable parameters:
| Property | Type | Default Value | Description |
|---|---|---|---|
| name | String | The name of the appender. | |
| bufferSize | int | 8192 | The size of the ByteBuffer internally used by the appender. |
| direct | boolean | false | If set to true, log events will be written directly to either FileDescriptor.out or FileDescriptor.err. This setting bypasses the buffering of System.out and System.err and might provide a performance comparable to a file appender. This setting is incompatible with the follow attribute. |
| follow | boolean | false | If set to true, the appender will honor reassignments of System.out (resp. System.err) via System.setOut (resp. System.setErr). Otherwise, the value of System.out (resp. System.err) at configuration time will be used. This setting is incompatible with the direct attribute. |
| ignoreExceptions | boolean | true | If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored. |
| immediateFlush | boolean | true | If set to true, the appender will flush its internal buffer after each event. |
| target | Target | SYSTEM_OUT | It specifies which standard output stream to use: SYSTEM_OUT - It uses the standard output. SYSTEM_ERR - It uses the standard error output. |
| filter | String | Allows filtering log events just before they are formatted and sent. | |
| layout | Layout | Formats log events. |
Log Table Configuration
Before you start using JDBC based logging, you should create a table to maintain all the log information. Following is the SQL Statement for creating the LOGS table −
CREATE TABLE LOGS
(
TIMESTAMP TIMESTAMP(6) NOT NULL,
LOGGER VARCHAR(50) NOT NULL,
LEVEL VARCHAR(10) NOT NULL,
MESSAGE VARCHAR(1000) NOT NULL
);
Sample Configuration File
Following is a sample configuration file log4j.properties for JDBCAppender which will is be used to log messages to a LOGS table.
appender.0.type = JDBC appender.0.name = JDBC appender.0.tableName = logs appender.0.bufferSize = 10 appender.0.connectionSource.type= DriverManager appender.0.connectionSource.connectionString = jdbc:mysql://localhost:3306/tutorials appender.0.connectionSource.username = guest appender.0.connectionSource.password = guest123 appender.0.connectionSource.driverClassName = com.mysql.cj.jdbc.Driver appender.0.col[0].type = ColumnMapping appender.0.col[0].name = timestamp appender.0.col[0].columnType = java.util.Date appender.0.col[1].type = ColumnMapping appender.0.col[1].name = level appender.0.col[1].pattern = %level appender.0.col[2].type = ColumnMapping appender.0.col[2].name = logger appender.0.col[2].pattern = %logger appender.0.col[3].type = ColumnMapping appender.0.col[3].name = message appender.0.col[3].pattern = %message # Define the root logger with appender file rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = JDBC
For MySQL database, you would have to use the actual DBNAME, user ID and password, where you have created LOGS table. The SQL statement is to execute an INSERT statement with the table name LOGS and the values to be entered into the table.
JDBCAppender does not need a layout to be defined explicitly. Instead, the SQL statement passed to it uses a PatternLayout.
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content −
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
<appenders>
<Jdbc name="databaseAppender" tableName="logs">
<DriverManager url="jdbc:mysql://localhost:3306/tutorials" username="guest" password="guest123" />
<Column name="level" pattern="%level" />
<Column name="logger" pattern="%logger" />
<Column name="message" pattern="%message" />
</Jdbc>
</appenders>
<loggers>
<root level="warn">
<appender-ref ref="databaseAppender"/>
</root>
</loggers>
</configuration>
Sample Program
The following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications.
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
Compile and Execute
Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the given steps −
Create log4j2.properties as shown above.
Create log4jDemo.java as shown above and compile it.
Execute log4jDemo binary to run the program.
Now check your LOGS table inside tutorials database and you would find the following entries −
mysql > select * from LOGS; +----------------------------+------------------------------+-------+----------------------------------+ | TIMESTAMP | LOGGER | LEVEL | MESSAGE | +----------------------------+------------------------------+-------+----------------------------------+ | 2025-09-07 13:53:25.617000 | com.tutorialspoint.log4jDemo | DEBUG | Hello this is an debug message | | 2025-09-07 13:53:25.620000 | com.tutorialspoint.log4jDemo | INFO | Hello this is an info message | +----------------------------+------------------------------+-------+----------------------------------+ 2 rows in set (0.00 sec)
log4j - Log Formatting
Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way.
All Layout objects receive a LoggingEvent object from the Appender objects. The Layout objects then retrieve the message argument from the LoggingEvent and apply the appropriate ObjectRenderer to obtain the String representation of the message.
The Layout Types
The top-level class in the hierarchy is the abstract class org.apache.logging.log4j.Layout. This is the base class for all other Layout classes in the log4j API.
The Layout class is defined as abstract within an application, we never use this class directly; instead, we work with its subclasses which are as follows:
The Layout Methods
This class provides a skeleton implementation of all the common operations across all other Layout objects and declares two abstract methods.
| Sr.No. | Methods & Description |
|---|---|
| 1 |
public abstract boolean ignoresThrowable()
It indicates whether the logging information handles any java.lang.Throwable object passed to it as a part of the logging event. If the Layout object handles the Throwable object, then the Layout object does not ignore it, and returns false. |
| 2 |
public abstract String format(LoggingEvent event)
Individual layout subclasses implement this method for layout specific formatting. |
Apart from these abstract methods, the Layout class provides concrete implementation for the methods listed below:
| Sr.No. | Methods & Description |
|---|---|
| 1 |
public String getContentType()
It returns the content type used by the Layout objects. The base class returns text/plain as the default content type. |
| 2 |
public String getFooter()
It specifies the footer information of the logging message. |
| 3 |
public String getHeader()
It specifies the header information of the logging message. |
Each subclass can return class-specific information by overriding the concrete implementation of these methods.
log4j - CSV Parameter Layout
If you want to generate your logging information in an CSV-formatted file, then you can use org.apache.logging.log4j.CSVParameterLayout to format your logging information.
The CSVParameterLayout class encodes only the parameters passed in the message of log event.
For example, consider the below log statements −
LOGGER.info("Record 1 {} {}", "arg1", "arg2");
LOGGER.error("Record 2 {} {} {}", "arg3", "arg4", "arg5", throwable);
The resulted logs will contain following entries in CSV format −
arg1,arg2 arg3,arg4,arg5
CSVParameterLayout Configuration
CSVParameterLayout can be configured with following parameters:
| Parameter | Type | Description |
|---|---|---|
| format | String | A predefined format name (Default, Excel, MySQL, RFC4180, TDF, etc.) accepted by CSVFormat |
| delimiter | Character | The field delimiter character |
| escape | Character | The escape character |
| quote | Character | The quote character |
| quoteMode | String | A quote mode name (ALL, ALL_NONE_NULL, MINIMAL, NON_NUMERIC, NONE, etc.) accepted by QuoteMode |
| nullString | String | The string to denote null values |
| recordSeparator | String | The record separator string |
| charset | Charset | The character encoding |
| header | String | The header to include when the stream is opened |
| footer | String | The footer to include when the stream is closed |
We need following jars in the classpath −
Example - Usage of CSVParameterLayout
Following is a simple configuration file for CSVParameterLayout:
log4j2.properties
# Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = CsvParameterLayout # Define the root logger with appender Console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Record 1 {} {}", "arg1", "arg2");
LOGGER.info("Record 2 {} {} {}", "arg1", "arg2", "arg3");
}
}
Output
Compile and run the above program. Console will print the following log information:
arg1,arg2 arg1,arg2,arg3
log4j - CSV Log Event Layout
If you want to encode your complete logging information in an CSV-formatted file, then you can use org.apache.logging.log4j.CSVLogEventLayout to format your logging information.
The CSVLogEventLayout class encodes all details of the message of log event.
For example, consider the below log statements −
LOGGER.info("Record 1 {} {}", "arg1", "arg2");
LOGGER.error("Record 2 {} {} {}", "arg3", "arg4", "arg5", throwable);
The resulted logs will contain following entries in CSV format −
0,1757242265192,DEBUG,1,main,5,Record 1 arg1 arg2,org.apache.logging.log4j.spi.AbstractLogger,com.tutorialspoint.Log4jDemo,,,com.tutorialspoint.Log4jDemo.main(Log4jDemo.java:12),{},[]
0,1757242265199,INFO,1,main,5,Record 2 arg1 arg2 arg3,org.apache.logging.log4j.spi.AbstractLogger,com.tutorialspoint.Log4jDemo,,,com.tutorialspoint.Log4jDemo.main(Log4jDemo.java:13),{},[]
CSVLogEventLayout Fields
CSVLogEventLayout generate records with following fields of a log event:
Time (in nanoseconds)
Time (in milliseconds)
Level
Thread ID
Thread name
Thread priority
Message (formatted, hence including parameters)
Logger FQCN
Logger name
Marker
Throwable
Source
Thread context map
Thread context stack
CSVLogEventLayout Configuration
CSVLogEventLayout can be configured with following parameters:
| Parameter | Type | Description |
|---|---|---|
| format | String | A predefined format name (Default, Excel, MySQL, RFC4180, TDF, etc.) accepted by CSVFormat |
| delimiter | Character | The field delimiter character |
| escape | Character | The escape character |
| quote | Character | The quote character |
| quoteMode | String | A quote mode name (ALL, ALL_NONE_NULL, MINIMAL, NON_NUMERIC, NONE, etc.) accepted by QuoteMode |
| nullString | String | The string to denote null values |
| recordSeparator | String | The record separator string |
| charset | Charset | The character encoding |
| header | String | The header to include when the stream is opened |
| footer | String | The footer to include when the stream is closed |
We need following jars in the classpath −
Example - Usage of CSVLogEventLayout
Following is a simple configuration file for CSVLogEventLayout:
log4j2.properties
# Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = CSVLogEventLayout # Define the root logger with appender Console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Record 1 {} {}", "arg1", "arg2");
LOGGER.info("Record 2 {} {} {}", "arg1", "arg2", "arg3");
}
}
Output
Compile and run the above program. Console will print the following log information:
0,1757242265192,DEBUG,1,main,5,Record 1 arg1 arg2,org.apache.logging.log4j.spi.AbstractLogger,com.tutorialspoint.Log4jDemo,,,com.tutorialspoint.Log4jDemo.main(Log4jDemo.java:12),{},[]
0,1757242265199,INFO,1,main,5,Record 2 arg1 arg2 arg3,org.apache.logging.log4j.spi.AbstractLogger,com.tutorialspoint.Log4jDemo,,,com.tutorialspoint.Log4jDemo.main(Log4jDemo.java:13),{},[]
log4j - HTMLLayout
If you want to generate your logging information in an HTML-formatted file, then you can use org.apache.logging.log4j.HTMLLayout to format your logging information.
The HTMLLayout class extends the abstract org.apache.logging.log4j.Layout class and overrides the format() method from its base class to provide HTML-style formatting.
It provides the following information to be displayed:
The time elapsed from the start of the application before a particular logging event was generated.
The name of the thread that invoked the logging request.
The level associated with this logging request.
The name of the logger and logging message.
The optional location information for the program file and the line number from which this logging was invoked.
HTMLLayout Methods
HTMLLayout is a very simple Layout object that provides the following methods:
| Sr.No. | Method & Description |
|---|---|
| 1 |
setContentType(String)
Sets the content type of the text/html HTML content. Default is text/html. |
| 2 |
setLocationInfo(String)
Sets the location information for the logging event. Default is false. |
| 3 |
setTitle(String)
Sets the title for the HTML file. Default is log4j Log Messages. |
Example - Usage of HTMLLayout
Following is a simple configuration file for HTMLLayout:
log4j2.properties
// Define a File Appender with HTMLLayout appender.0.type = File appender.0.name = MAIN appender.0.fileName = logs/htmlLayout.html appender.0.layout.type = HTMLLayout appender.0.layout.Title=HTML Layout Example appender.0.layout.LocationInfo=true rootLogger.level = DEBUG // Attach the appender to rootLogger rootLogger.appenderRef.0.ref = MAIN rootLogger.appenderRef.0.level = INFO
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
Output
Compile and run the above program. It would create an htmlLayout.html file in logs directory which would have the following log information:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8"/>
<title>HTML Layout Example</title>
<style type="text/css">
<!--
body, table {font-family:arial,sans-serif; font-size: medium
;}th {background: #336699; color: #FFFFFF; text-align: left;}
-->
</style>
</head>
<body bgcolor="#FFFFFF" topmargin="6" leftmargin="6">
<hr size="1" noshade="noshade">
Log session start time Fri Sep 05 20:06:22 IST 2025<br>
<br>
<table cellspacing="0" cellpadding="4" border="1" bordercolor="#224466" width="100%">
<tr>
<th>Time</th>
<th>Thread</th>
<th>Level</th>
<th>Logger</th>
<th>File:Line</th>
<th>Message</th>
</tr>
<tr>
<td>637</td>
<td title="main thread">main</td>
<td title="Level">INFO</td>
<td title="com.tutorialspoint.Log4jDemo logger">com.tutorialspoint.Log4jDemo</td>
<td>Log4jDemo.java:14</td>
<td title="Message">Hello this is an info message</td>
</tr>
</table>
<br>
</body></html>
You would use a web browser to open htmlLayout.html file.
One of the big advantages of having the log file in HTML format is that it can be published as a web page for remote viewing.
log4j - PatternLayout
If you want to generate your logging information in a particular format based on a pattern, then you can use org.apache.log4j.PatternLayout to format your logging information.
The PatternLayout class extends the abstract org.apache.logging.log4j.Layout class and overrides the format() method to structure the logging information according to a supplied pattern.
PatternLayout is also a simple Layout object that provides the following-Bean Property which can be set using the configuration file:
| Sr.No. | Property & Description |
|---|---|
| 1 |
conversionPattern
Sets the conversion pattern. Default is %r [%t] %p %c %x - %m%n |
Pattern Conversion Characters
The following table explains the characters used in the above pattern and all other characters that you can use in your custom pattern:
| Conversion Character | Meaning |
|---|---|
| c | Used to output the category of the logging event. For example, for the category name "a.b.c" the pattern %c{2} will output "b.c". |
| C | Used to output the fully qualified class name of the caller issuing the logging request. For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass". |
| d | Used to output the date of the logging event. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. |
| F | Used to output the file name where the logging request was issued. |
| l | Used to output location information of the caller which generated the logging event. |
| L | Used to output the line number from where the logging request was issued. |
| m | Used to output the application supplied message associated with the logging event. |
| M | Used to output the method name where the logging request was issued. |
| n | Outputs the platform dependent line separator character or characters. |
| p | Used to output the priority of the logging event. |
| r | Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event. |
| t | Used to output the name of the thread that generated the logging event. |
| x | Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event. |
| X | The X conversion character is followed by the key for the MDC. For example, X{clientIP} will print the information stored in the MDC against the key clientIP. |
| % | The literal percent sign. %% will print a % sign. |
Format Modifiers
By default, the relevant information is displayed as output as is. However, with the aid of format modifiers, it is possible to change the minimum field width, the maximum field width, and justification.
Following table covers various modifiers scenarios:
| Format modifier | left justify | minimum width | maximum width | comment |
|---|---|---|---|---|
| %20c | false | 20 | none | Left pad with spaces if the category name is less than 20 characters long. |
| %-20c | true | 20 | none | Right pad with spaces if the category name is less than 20 characters long. |
| %.30c | NA | none | 30 | Truncate from the beginning if the category name is longer than 30 characters. |
| %20.30c | false | 20 | 30 | Left pad with spaces if the category name is shorter than 20 characters. However, if the category name is longer than 30 characters, then truncate from the beginning. |
| %-20.30c | true | 20 | 30 | Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |
Example - Usage of PatternLayout
Following is a simple configuration file for PatternLayout:
log4j2.properties
// Define a Console Appender with PatternLayout
appender.0.type = Console
appender.0.name = CONSOLE
appender.0.layout.type = PatternLayout
appender.0.layout.pattern = %d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n
rootLogger.level = DEBUG
// Attach the appender to rootLogger
rootLogger.appenderRef.0.ref = CONSOLE
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
Compile and run the above program. It would print following log information on the console:
2025-09-05-main-[]-DEBUG-com.tutorialspoint.Log4jDemo:Hello this is an debug message 2025-09-05-main-[]-INFO -com.tutorialspoint.Log4jDemo:Hello this is an info message
log4j - Json Template Layout
If you want to encode your complete logging information in a JSON formatted file, then you can use org.apache.logging.log4j.JsonTemplateLayout to format your logging information.
JsonTemplateLayout is highly customizable, efficient layout. It is a garbage-free JSON generating layout as well. LogEvents are genereated according to the structure described by the JSON template provided in classpath.
CustomLayout.json
{
"instant": {
"$resolver": "timestamp",
"pattern": {
"format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"timeZone": "UTC"
}
},
"aConstant": 1,
"message": {
"$resolver": "message",
"stringified": true
}
}
log4j2.properties
appender.0.layout.type = JsonTemplateLayout appender.0.layout.eventTemplateUri = classpath:CustomLayout.json
log4j2.xml
<Appenders>
<Console name="logFile">
<JsonTemplateLayout eventTemplateUri="classpath:CustomLayout.json"/>
</Appenders>
Example - Usage of JsonTemplateLayout
Following is a simple configuration file for JsonTemplateLayout:
log4j2.properties
# Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = JsonTemplateLayout appender.0.layout.eventTemplateUri = classpath:CustomLayout.json # Define the root logger with appender Console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
Now create a template json in current classpath:
CustomLayout.json
{
"instant": {
"$resolver": "timestamp",
"pattern": {
"format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"timeZone": "UTC"
}
},
"aConstant": 1,
"message": {
"$resolver": "message",
"stringified": true
}
}
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
Output
Compile and run the above program. Console will print the following log information:
{"instant":"2025-09-07T14:58:18.268Z","aConstant":1,"message":"Hello this is an debug message"}
{"instant":"2025-09-07T14:58:18.273Z","aConstant":1,"message":"Hello this is an info message"}
log4j - Logging in Files
Apache log4j provides various Appender objects, each of which can be used to log data in files as per customized needs.
File Appenders
Following are most commonly Use Cases:
XML Based Configuration
Following is a sample XML Based configuration of a FileAppender
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
<Appenders>
<File name="logFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="logFile"/>
</Root>
</Loggers>
</Configuration>
We're using Appenders tag to contain a File tag to define the File Appender which is further writing to a log file app.log using PatternLayout.
Properties Based Configuration
Following is a sample properties Based configuration of a FileAppender
log4j2.properties
appender.0.type = File
appender.0.name = logFile
appender.0.fileName = logs/app.log
appender.0.layout.type = PatternLayout
appender.0.layout.pattern = %d %p %c{1.} [%t] %m%n
rootLogger.level = ERROR
rootLogger.appenderRef.0.ref = FILE
log4j - FileAppender
A FileAppender is an object of ObjectStreamAppender and is used to write to a file named using fileName parameter in log4j configuration.
log4j2.properties
appender.0.type = File appender.0.name = logFile
log4j2.xml
<Appenders>
<File name="logFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
FileAppender uses FileManger, a subclass of OutputStreamManager to perform the I/O.
FileAppender Configuration
FileAppender has the following configurable parameters:
| Property | Type | Default Value | Description |
|---|---|---|---|
| fileName | Path | The path to the current log file If the folder containing the file does not exist, it will be created. | |
| name | String | The name of the appender. | |
| bufferSize | int | 8192 | The size of the ByteBuffer internally used by the appender. |
| ignoreExceptions | boolean | true | If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored. |
| immediateFlush | boolean | true | If set to true, the appender will flush its internal buffer after each event. |
| filter | String | Allows filtering log events just before they are formatted and sent. | |
| layout | Layout | Formats log events. | |
| append | boolean | true | If true, the log file will be opened in APPEND mode. On most systems this guarantees atomic writes to the end of the file, even if the file is opened by multiple applications. |
| bufferedIo | boolean | true | If set to true, Log4j Core will format each log event in an internal buffer, before sending it to the underlying resource. |
| createOnDemand | boolean | false | The appender creates the file on-demand. The appender only creates the file when a log event passes all filters and is routed to this appender. Defaults to false. |
| filePermissions | PosixFilePermissions | null | If not null, it specifies the POSIX file permissions to apply to each created file. The permissions must be provided in the format used by PosixFilePermissions.fromString(), e.g. rw-rw----. The underlying files system shall support POSIX file attribute view. |
| fileOwner | String | null | If not null, it specifies the file owner to apply to each created file. The underlying files system shall support file owner attribute view. |
| fileGroup | String | null | If not null, it specifies the file group owner to apply to each created file. The underlying files system shall support POSIX file attribute view. |
| locking | boolean | false | If true, Log4j will lock the log file at each log event. Note that the effects of this setting depend on the Operating System: some systems like most POSIX OSes do not offer mandatory locking, but only advisory file locking. This setting can also reduce the performance of the appender. |
RollFile Appender Configuration Examples
Following is a sample configuration file log4j2.properties for FileAppender −
log4j2.properties
# Define the file appender
appender.0.type = File
# Set the name of the file appender
appender.0.name = logFile
# Set the name of the file
appender.0.fileName = logs/app.log
# Define the layout for file appender
appender.0.layout.type = PatternLayout
appender.0.layout.pattern = %d %p %c{1.} [%t] %m%n
# Define the root logger with appender file
rootLogger.level = DEBUG
rootLogger.appenderRef.0.ref = logFile
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content:
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
<Appenders>
<File name="logFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="logFile"/>
</Root>
</Loggers>
</Configuration>
Example - Usage of FileAppender
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
We're using log4j2.properties file.
Output
Compile and run the above program. It would create a app.log file in logs directory which would have the following log information:
2025-09-06 07:05:27,262 DEBUG c.t.Log4jDemo [main] Hello this is an debug message 2025-09-06 07:05:27,264 INFO c.t.Log4jDemo [main] Hello this is an info message
log4j - Separate folder per month
You may want to write your log messages into sepearate folder on monthly basis. We're creating a separate folder for each month.
To write your logging information into multiple files, you would have to use org.apache.logging.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.
log4j2.properties
appender.0.type = RollingFile appender.0.name = logFile
log4j2.xml
<Appenders>
<RollingFile name="logFile" filePattern="logs/%d{yyyy-MM}/%d{yyyy-MM-dd}.log.zip">
<JsonTemplateLayout/>
<DirectWriteRolloverStrategy>
<Delete basePath="logs" maxDepth="2">
<IfLastModified age="P90D"/>
</Delete>
</DirectWriteRolloverStrategy>
<TimeBasedTriggeringPolicy/>
</RollingFile>
</Appenders>
RollingFileAppender Configuration
RollingFileAppender has the following configurable parameters:
| Property | Type | Default Value | Description |
|---|---|---|---|
| fileName | Path | The path to the current log file If the folder containing the file does not exist, it will be created. | |
| filePattern | Path | The pattern for the archived log files. If fileName is null, the file pattern will also be used for the current file. | |
| name | String | The name of the appender. | |
| bufferSize | int | 8192 | The size of the ByteBuffer internally used by the appender. |
| bufferedTo | boolean | true | If set to true, Log4j Core will format each log event in an internal buffer, before sending it to the underlying resource. The RandomAccessRollingFile Appender always enables the internal buffer. |
| ignoreExceptions | boolean | true | If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored. |
| immediateFlush | boolean | true | If set to true, the appender will flush its internal buffer after each event. |
| filter | String | Allows filtering log events just before they are formatted and sent. | |
| layout | Layout | Formats log events. | |
| triggerPolicy | TriggeringPolicy | Determines when to archive the current log file. | |
| RolloverStrategy | RolloverStrategy | Determines the actions performed during a rollover. | |
| append | boolean | true | If true, the log file will be opened in APPEND mode. On most systems this guarantees atomic writes to the end of the file, even if the file is opened by multiple applications. |
| bufferedIo | boolean | true | If set to true, Log4j Core will format each log event in an internal buffer, before sending it to the underlying resource. |
| createOnDemand | boolean | false | The appender creates the file on-demand. The appender only creates the file when a log event passes all filters and is routed to this appender. Defaults to false. |
| filePermissions | PosixFilePermissions | null | If not null, it specifies the POSIX file permissions to apply to each created file. The permissions must be provided in the format used by PosixFilePermissions.fromString(), e.g. rw-rw----. The underlying files system shall support POSIX file attribute view. |
| fileOwner | String | null | If not null, it specifies the file owner to apply to each created file. The underlying files system shall support file owner attribute view. |
| fileGroup | String | null | If not null, it specifies the file group owner to apply to each created file. The underlying files system shall support POSIX file attribute view. |
| locking | boolean | false | If true, Log4j will lock the log file at each log event. Note that the effects of this setting depend on the Operating System: some systems like most POSIX OSes do not offer mandatory locking, but only advisory file locking. This setting can also reduce the performance of the appender. |
RollingFileAppender Configuration Examples
Following is a sample configuration file log4j2.properties for RollingFileAppender −
log4j2.properties
# Define the rolling file appender
appender.0.type = RollingFile
appender.0.name = logFile
# Set the file pattern
appender.0.filePattern = logs/%d{yyyy-MM]/%d{yyyy-MM-dd}.log.zip
appender.0.layout.type = JsonTemplateLayout
# set the roll over startegy
# we're creating a new log file every day
# and deleting 15 days old log files
appender.0.strategy.type = DirectWriteRolloverStrategy
appender.0.strategy.delete.type = Delete
appender.0.strategy.delete.basePath = logs
appender.0.strategy.delete.maxDepth = 2
appender.0.strategy.delete.0.type = IfLastModified
appender.0.strategy.delete.0.age = P15D
appender.0.policy.type = TimeBasedTriggeringPolicy
# Define the root logger with appender file
rootLogger.level = DEBUG
rootLogger.appenderRef.0.ref = logFile
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content:
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
<Appenders>
<RollingFile name="logFile" filePattern="logs/%d{yyyy-MM}/%d{yyyy-MM-dd}.log.zip">
<JsonTemplateLayout/>
<DirectWriteRolloverStrategy>
<Delete basePath="logs" maxDepth="2">
<IfLastModified age="P90D"/>
</Delete>
</DirectWriteRolloverStrategy>
<TimeBasedTriggeringPolicy/>
</RollingFile>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="logFile"/>
</Root>
</Loggers>
</Configuration>
Example - Usage of FileAppender
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
We're using log4j2.properties file.
Output
Compile and run the above program. It would create a folder similar to 2025-09-07 folder in logs directory which contains a log file having the following log information:
{"@timestamp":"2025-09-07T03:33:26.911Z","ecs.version":"1.2.0","log.level":"DEBUG","message":"Hello this is an debug message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
{"@timestamp":"2025-09-07T03:33:26.915Z","ecs.version":"1.2.0","log.level":"INFO","message":"Hello this is an info message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
log4j - Daily Log File Generation
There may be a requirement to generate your log files on a daily basis to keep a clean record of your logging information.
To write your logging information into multiple files, you would have to use org.apache.logging.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.
log4j2.properties
appender.0.type = RollingFile appender.0.name = logFile
log4j2.xml
<Appenders>
<RollingFile name="logFile" filePattern="logs/app.%d{yyyy-MM-dd}.log.zip">
<JsonTemplateLayout/>
<DirectWriteRolloverStrategy>
<Delete basePath="logs">
<IfFileName regex="app\.\d{4}-\d{2}-\d{2}\.log\.zip"/>
<IfLastModified age="P15D"/>
</Delete>
</DirectWriteRolloverStrategy>
<TimeBasedTriggeringPolicy/>
</RollingFile>
</Appenders>
RollingFileAppender Configuration
RollingFileAppender has the following configurable parameters:
| Property | Type | Default Value | Description |
|---|---|---|---|
| fileName | Path | The path to the current log file If the folder containing the file does not exist, it will be created. | |
| filePattern | Path | The pattern for the archived log files. If fileName is null, the file pattern will also be used for the current file. | |
| name | String | The name of the appender. | |
| bufferSize | int | 8192 | The size of the ByteBuffer internally used by the appender. |
| bufferedTo | boolean | true | If set to true, Log4j Core will format each log event in an internal buffer, before sending it to the underlying resource. The RandomAccessRollingFile Appender always enables the internal buffer. |
| ignoreExceptions | boolean | true | If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored. |
| immediateFlush | boolean | true | If set to true, the appender will flush its internal buffer after each event. |
| filter | String | Allows filtering log events just before they are formatted and sent. | |
| layout | Layout | Formats log events. | |
| triggerPolicy | TriggeringPolicy | Determines when to archive the current log file. | |
| RolloverStrategy | RolloverStrategy | Determines the actions performed during a rollover. | |
| append | boolean | true | If true, the log file will be opened in APPEND mode. On most systems this guarantees atomic writes to the end of the file, even if the file is opened by multiple applications. |
| bufferedIo | boolean | true | If set to true, Log4j Core will format each log event in an internal buffer, before sending it to the underlying resource. |
| createOnDemand | boolean | false | The appender creates the file on-demand. The appender only creates the file when a log event passes all filters and is routed to this appender. Defaults to false. |
| filePermissions | PosixFilePermissions | null | If not null, it specifies the POSIX file permissions to apply to each created file. The permissions must be provided in the format used by PosixFilePermissions.fromString(), e.g. rw-rw----. The underlying files system shall support POSIX file attribute view. |
| fileOwner | String | null | If not null, it specifies the file owner to apply to each created file. The underlying files system shall support file owner attribute view. |
| fileGroup | String | null | If not null, it specifies the file group owner to apply to each created file. The underlying files system shall support POSIX file attribute view. |
| locking | boolean | false | If true, Log4j will lock the log file at each log event. Note that the effects of this setting depend on the Operating System: some systems like most POSIX OSes do not offer mandatory locking, but only advisory file locking. This setting can also reduce the performance of the appender. |
RollingFileAppender Configuration Examples
Following is a sample configuration file log4j2.properties for RollingFileAppender −
log4j2.properties
# Define the rolling file appender
appender.0.type = RollingFile
appender.0.name = logFile
# Set the file pattern
appender.0.filePattern = logs/app.%d{yyyy-MM-dd}.log.zip
appender.0.layout.type = JsonTemplateLayout
# set the roll over startegy
# we're creating a new log file every day
# and deleting 15 days old log files
appender.0.strategy.type = DirectWriteRolloverStrategy
appender.0.strategy.delete.type = Delete
appender.0.strategy.delete.basePath = logs
appender.0.strategy.delete.0.type = IfFileName
appender.0.strategy.delete.0.regex = app\\.\\d{4}-\\d{2}-\\d{2}\\.log\\.zip
appender.0.strategy.delete.1.type = IfLastModified
appender.0.strategy.delete.1.age = P15D
appender.0.policy.type = TimeBasedTriggeringPolicy
# Define the root logger with appender file
rootLogger.level = DEBUG
rootLogger.appenderRef.0.ref = logFile
If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content:
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
<Appenders>
<RollingFile name="logFile" filePattern="logs/app.%d{yyyy-MM-dd}.log.zip">
<JsonTemplateLayout/>
<DirectWriteRolloverStrategy>
<Delete basePath="/var/log">
<IfFileName regex="app\.\d{4}-\d{2}-\d{2}\.log\.gz"/>
<IfLastModified age="P15D"/>
</Delete>
</DirectWriteRolloverStrategy>
<TimeBasedTriggeringPolicy/>
</RollingFile>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="logFile"/>
</Root>
</Loggers>
</Configuration>
Example - Usage of FileAppender
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4jDemo{
/* Get actual class name to be printed on */
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("Hello this is an debug message");
LOGGER.info("Hello this is an info message");
}
}
We're using log4j2.properties file.
Output
Compile and run the above program. It would create a file similar to app.2025-09-06 file in logs directory which would have the following log information:
{"@timestamp":"2025-09-06T08:20:15.900Z","ecs.version":"1.2.0","log.level":"DEBUG","message":"Hello this is an debug message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}
{"@timestamp":"2025-09-06T08:20:15.904Z","ecs.version":"1.2.0","log.level":"INFO","message":"Hello this is an info message","process.thread.name":"main","log.logger":"com.tutorialspoint.Log4jDemo"}