Log4j2 Properties File Example

Learn to configure log4j2.properties file to output the log statements to the console, rolling files etc. Learn to configure log4j2 appenders, levels and patterns.

Upgrade Notice: If not upgraded already, it is highly recommended to upgrade Log4j2 to the latest version which has the fix for a recently found vulnerability CVE-2021-45046. Read the latest updates to the library here.

1. Log4j2 Dependencies

Please note that using Log4j2 with SLF4J is recommended approach.

1.1. Maven

To include Log4j2, include the latest version of log4j-core and log4j-api dependencies.

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.19.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>

1.2. Gradle

dependencies {
    implementation 'org.apache.logging.log4j:log4j-api:2.19.0'
    implementation 'org.apache.logging.log4j:log4j-core:2.19.0'
}

2. The Default Logging Behavior

The default behavior kicks in when:

  • there is no log4j.configurationFile property is present in the startup arguments or when this property doesn’t point to a valid configuration file.
  • there is no valid log4j2-test.[xml|properties|yaml|json] file present in the classpath.
  • there is no log4j2.[xml|properties|yaml|json] file present in the classpath.

By default, Log4j2 will use the ConsoleAppender to write the log message to the console.

Also, the root logger is default 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.

3. Configuring log4j2.properties for Console Logging

We can use below log4j2.properties file logging output into the console. Please note that if no configuration file can be located then DefaultConfiguration will be used, and that also logs on to the console.

# 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

4. 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

5. Scanning 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.

Log4j2.properties file location
Log4j2.properties file location

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 log4j2.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 log4j2.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.

6. Demo

Let’s write a java class and a few log statements to verify that logs are appearing in the console and log file.

To log the statements, we get the Logger instance by using the SLF4J LoggerFactory class and its getLogger() method. Then we use various methods 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, we 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/:?]

Happy Learning !!

Download Sourcecode

Comments

Subscribe
Notify of
guest
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode