Learn to configure log4j2.properties file to output the log statements to console, rolling files etc. Learn to configure log4j2 appenders, levels and patterns.
Apache Log4j2 is an upgrade to Log4j 1.x that provides significant improvements over its predecessor such as performance improvement, automatic reloading of modified configuration files, Java 8 lambda support and custom log levels.
If not upgraded already, it is highly recommended to upgrade Log4j2 to the latest version 2.16.0 which has the fix for a recently found vulnerability CVE-2021-45046. Read the latest updates to the library here.
1. Log4j2 Dependencies
Find the latest version from this link. Please note that using Log4j2 with SLF4J is recommended approach.
1.1. Maven
To include Log4j2, include below maven dependency in the project.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.16.0</version>
</dependency>
1.2. Gradle
dependencies {
implementation 'org.apache.logging.log4j:log4j-api:2.16.0'
implementation 'org.apache.logging.log4j:log4j-core:2.16.0'
}
2. Configuring log4j2.properties for Console Logging
We can use below log4j2.properties
file logging output into console. Please note that if no configuration file could be located then DefaultConfiguration
will be used.
Log4j2 default logging also causes logging output to go to the console.
# Extra logging related to initialization of Log4j
# Set to debug or trace if log4j initialization is failing
status = warn
# Name of the configuration
name = ConsoleLogConfigDemo
# Console appender configuration
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Root logger level
rootLogger.level = debug
# Root logger referring to console appender
rootLogger.appenderRef.stdout.ref = consoleLogger
3. Configuring log4j2.properties for Rolling Files
We can use the below log4j2.properties
file logging output with time and size based rolling files.
status = warn
name= RollingFileLogConfigDemo
# Log files location
property.basePath = c:/temp/logs
# RollingFileAppender name, pattern, path and rollover policy
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName= ${basePath}/app.log
appender.rolling.filePattern= ${basePath}/app_%d{yyyyMMdd}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%l] - %msg%n
appender.rolling.policies.type = Policies
# RollingFileAppender rotation policy
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size = 10MB
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}
appender.rolling.strategy.delete.maxDepth = 10
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified
# Delete all files older than 30 days
appender.rolling.strategy.delete.ifLastModified.age = 30d
# Configure root logger
rootLogger.level = debug
rootLogger.appenderRef.rolling.ref = fileLogger
4. Log4j2.properties File in Classpath
We should put log4j2.properties
anywhere in the application’s classpath. Log4j2 will scan all classpath locations to find out this file and then load it.
We have put the file in resources
folder.

If we are using an external log4j2 configuration file, then we can provide the path of the configuration file using the application startup parameter or system property log4j.configurationFile
. Note that this property value is not restricted to a location on the local file system and may contain a URL.
-Dlog4j2.configurationFile=file:/home/lokesh/log4j2.properties
A commonly seen approach is to set the log4j.configurationFile
property in the method annotated with @BeforeAll in the junit test class. This will allow an arbitrarily named file to be used during the test.
5. Demo
Let’s write a java class and write a few log statements to verify that logs are appearing in the console and log file as well.
To log the statements, we get the Logger
instance by using the SLF4J LoggerFactory class and its getLogger method. Then we use various methods of the Logger
to write the log records, such as info(), error() and debug().
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
public static void main(final String[] args)
{
Logger logger = LoggerFactory.getLogger(Main.class);
logger.debug("Debug Message Logged !!!");
logger.info("Info Message Logged !!!");
logger.error("Error Message Logged !!!", new NullPointerException("NullError"));
}
}
Now when you run the above program, you will get the below log statements in the console.
2021-12-14 14:26:32.737 DEBUG [main] [com.howtodoinjava.demo.slf4j.Main.main (Main.java:10)] - Debug Message Logged !!!
2021-12-14 14:26:32.739 INFO [main] [com.howtodoinjava.demo.slf4j.Main.main (Main.java:11)] - Info Message Logged !!!
2021-12-14 14:26:32.739 ERROR [main] [com.howtodoinjava.demo.slf4j.Main.main (Main.java:12)] - Error Message Logged !!!
java.lang.NullPointerException: NullError
at com.howtodoinjava.demo.slf4j.Main.main (Main.java:12) [classes/:?]
6. The Default Behavior
The default behavior kicks in when is no log4j.configurationFile
property is present in the startup arguments; or when this property doesn’t point to a valid configuration file. Also, there is no valid log4j2-test.[xml|properties|yaml|json] file and log4j2.[xml|properties|yaml|json] file is present in the classpath..
By default, Log4j2 will use the ConsoleAppender to write the log message to the console.
Also, by default, the root logger is defined for the ERROR level. This means that only ERROR log statements will be visible and INFO, DEBUG, TRACE level messages will not be visible.
Happy Learning !!
Can someone please advise how to specify the log file name (appender.rolling.fileName) at runtime? Like -Dlog4j2.configurationFile=file://${log4jFile} is there something to set the filename as well ?
You can pass the file name as startup argument. For example
-Dlog4jFile=path-and-file-name
.Sorry, am not sure if am missing something.
I kept the property as appender.rolling.fileName= ${basePath}/${File}.log
and passed the file name as
-Dlog4jFile=path-and-file-name.
Its writing logs to file name “${file}” and not the value present in the variable ${File} passed in -D
Pass this argument.
-Dfile=path-and-file-name.
Is it:
-Dlog4j2.configurationFile
or:
-Dlog4j.configurationFile
?
“log4j2.configurationFile” is the recommended property name. “log4j.configurationFile” is legacy name, but seems it is still supported.
That doesn’t work in version 2.12.4.
Another thing, in log4j2 it seems to depend on the filename extension; a filename that doesn’t end with “.properties” seems to be parsed as XML (which fails).
How can I set threshold as custom in property file appender
Not sure what you want to acheive? Can you please share the code/config you are trying; and what error you get?
can you give one example of monitorInterval in log4j2.properties
hi ,
how to disable rootLogger in log4j2 ?
You can set
additivity
tofalse
so that the log message will only go to the named logger, and not to the root logger.This is the first example that actually got something to log on the console for me!!! Although not sure what any of it means….most documention on apache log4j is old and not update. Thanks for this tutorial. Off to go read more….
Tried to log details into the file using the rolling file property content showed in the explanation. But only the last log message is available in the file.
I my example I logged 3 debug message – 1. successful login 2. Verified with incorrect data and 3. verified with null data.
Only verified with null data is displayed in my log file. But I can see all the messages in the console.
How to use external properties file
I am trying to log in Apache camel project. I used the same above dependencies and properties. I am getting below warnngs.
log4j:WARN No appenders could be found for logger (org.apache.camel.util.LRUCacheFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
What happens if there are more than one log4j2.properties file in the classpath?
There is a detailed lookup order listed here : http://logging.apache.org/log4j/2.x/manual/configuration.html
What if i want to refer log4j2.properties file from local file system and not from class path
only error level log is printed in console.
also there is no log in the file created.
i also tried but file not created
What do the following lines, copied from your log4j2.properties example above,, do?
status = error
name = PropertiesConfig