Log4J 2 Configuration: Using the Properties File - DZone (2024)

Log4J 2 is a logging framework designed to address the logging requirements of enterprise applications. Its predecessor Log4J 1.x has been around for more than one and a half decade and is still one of the most widely used Java logging frameworks. Log4J has even been ported to the .NET world. Log4net is one of the most popular logging frameworks for Microsoft’s .NET environment.

Log4J 2 goes steps ahead by removing the inherent architectural flaws of Log4J 1.x. Since the initial release of Log4J 2 on August 2015, it’s quickly being adopted by the developer community. I wrote an introductory post on Log4J 2 here. If you have not read it, I recommend starting with the introductory post first. In this post, I will discuss how to configure Log4J 2 using a properties configuration file. This is just one of several ways you can configure Log4J 2.

What Are Log4J 2 Configuration Files?

Log4J 2 provides various components, such as loggers, appenders, and layouts that work together to perform logging in an application. As different applications have different logging requirements, you’re ableto configure LogJ 2 accordingly. Also, you will often need to keep changing Log4J 2 configurations of an application across its deployment lifecycle. Forexample, it is common to set the logging level to DEBUG during development, and later switch it to ERROR to avoid filling your logs with excessive debug information. Similarly, during local development, you can work with the console appender to avoid file I/O overheads and in other deployment environments,set a file appender or some other persistent destination to preserve log messages.

You can configure Log4J 2 either programmatically in your application or through configuration files, such as properties, XML, JSON, and YAML residing on your project classpath. Through theuse of configuration files, you have the flexibility of changing the various configuration options without modifying your application code. In this post, we’re going to look at using theproperties file.

Setting Up Log4J 2 to Use the Properties File

Unlike its predecessor Log4J 1.x, Log4J 2 did not support configuration through the properties file when it was initially released. It was from Log4J 2.4 that support for the properties file was again added, but with a completely different syntax.

Log4J4 Maven Dependencies

To use Log4J 2 in your application, you need to ensure that the Log4J 2 jars are on your project classpath. If you intend to use theproperties file, give extra attention to ensure that you have the Log4J 2.4 or greater jars on the classpath. Otherwise, your properties file will not get picked.
Whenusing Maven, specify the following Log4J 2 dependencies.

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

Log4J 2 Spring Boot Dependencies

If you want to use Log4J 2 in a Spring Boot project, things can be a bit tricky. Simply adding the dependencies above won’t work as Spring Boot will first find the defaultLogbackclassic on the classpath, and will use it. Therefore, you need to exclude the default dependency of the Spring Boot starter on Logback classic, and instead include the Spring Boot starter dependency on Log4J 2, like this:

. . .<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId></dependency>. . .

This will configure Spring Boot to use Log4J 2, but with a catch – You still won’t be able to use theproperties file for configuration. As of Spring Boot 1.3.3 Release, Spring Boot starter dependency on Log4J 2 is for Log4J 2.1, and as I have already mentioned it is from Log4J 2.4 onward that the properties file is supported. Therefore, you need to explicitly specify dependencies of Log4J 2.4 or above after excluding Spring Boot starter logging, like this.

. . .<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions></dependency><dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.5</version></dependency><dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.5</version></dependency>. . .

The above dependencies will set up Log4J 2 to use theproperties file in a Spring Boot application.

Configuring Log4J 2 Using the Properties File

By default, Log4J 2 looks for a properties file with the namelog4j2.properties in the classpath. In a Spring Boot application, thelog4j2.properties file will typically be in the resources folder.

Before we start configuring Log4J 2, we will write a Java class to generatelog messages viaLog4J 2.

Log4J2PropertiesConf.java

package guru.springframework.blog.log4j2properties;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;public class Log4J2PropertiesConf { private static Logger logger = LogManager.getLogger(); public void performSomeTask(){ logger.debug("This is a debug message"); logger.info("This is an info message"); logger.warn("This is a warn message"); logger.error("This is an error message"); logger.fatal("This is a fatal message"); }}

To test theLog4J2PropertiesConf class above, we will write aJUnit test class.

Log4J2PropertiesConfTest.java

package guru.springframework.blog.log4j2properties;import org.junit.Test;import static org.junit.Assert.*;public class Log4J2PropertiesConfTest { @Test public void testPerformSomeTask() throws Exception { Log4J2PropertiesConf log4J2PropertiesConf=new Log4J2PropertiesConf(); log4J2PropertiesConf.performSomeTask(); }}

We will now configure Log4J 2 using a properties file. Like any other Java properties file, alog4j2.properties file is a set of key-value pairs with options to configure the various components of Log4J 2, such as loggers, appenders, and layouts. A basiclog4j2.properties file starts with a name, optional properties to be used in other parts of the file, and appender declarations.

name=PropertiesConfigproperty.filename = logsappenders = console, file. . .

The preceding code declares two appenders, namedconsole andfile. Next, let’s configure both the appenders to write log messages to the console and a file. The configuration code for the appenders is this.

. . .appender.console.type = Consoleappender.console.name = STDOUTappender.console.layout.type = PatternLayoutappender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%nappender.file.type = Fileappender.file.name = LOGFILEappender.file.fileName=${filename}/propertieslogs.logappender.file.layout.type=PatternLayoutappender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n. . .

In the code above we configured two appenders: One to write log messages to the console and the other to a log file. Both the appenders use pattern layouts that are configurable with conversion pattern strings to format log messages. Theappender.console.layout.pattern property specifies the pattern string. You can learn more about the pattern layout and conversion pattern stringshere. For the file appender, we used theappender.file.fileName property to specify the name and location of the log file that Log4J 2 will generate. Here, notice the${filename} declaration that we used as a substitution for theproperty.filename property we declared earlier.

Next, we will configure the loggers, starting from the root logger.

. . .rootLogger.level = debugrootLogger.appenderRefs = stdoutrootLogger.appenderRef.stdout.ref = STDOUT. . .

In the code above, we configured the root logger to log debug and its lower level messages to the console (stdout). When we run theLog4J2PropertiesConfTest test class, the output in the IntelliJ console will be similar to this.

Log4J 2 Configuration: Using the Properties File - DZone (1)

The completelog4j2.properties file is as follows:

log4j2.properties

name=PropertiesConfigproperty.filename = logsappenders = console, fileappender.console.type = Consoleappender.console.name = STDOUTappender.console.layout.type = PatternLayoutappender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%nappender.file.type = Fileappender.file.name = LOGFILEappender.file.fileName=${filename}/propertieslogs.logappender.file.layout.type=PatternLayoutappender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%nloggers=filelogger.file.name=guru.springframework.blog.log4j2propertieslogger.file.level = debuglogger.file.appenderRefs = filelogger.file.appenderRef.file.ref = LOGFILErootLogger.level = debugrootLogger.appenderRefs = stdoutrootLogger.appenderRef.stdout.ref = STDOUT

When we run theLog4J2PropertiesConfTest test class now, log messages will be sent to thelogs/propertieslogs.log by the file logger and additively to the console by the root logger. The following figure shows the log messages sent to the file and console in IntelliJ.

Log4J 2 Configuration: Using the Properties File - DZone (2)

In the example above, it is due to logger additivity that caused log messages to be sent to the file by the logger and additively to the console by the root logger. You can override this default behavior by setting theadditivity flag of a logger tofalse.

. . .logger.file.additivity = false. . .

The property above configures our file appender so thatitis no longer additive, thuslog messages will only be sent to the file.

Appender additivity can be somewhat confusing. I suggest reviewing theLog4J 2 documentation on the subject, where they have some good examples of how this works.

Summary

Using the properties file is one of the several options you have to configure Log4J 2. Log4J 2 is gradually moving to XML configuration and the new JSONand YAML configurations. Properties configuration cannot handle some advanced features, such as custom error handlers, time-based rolling policies, nested appenders, and special types of appenders, such as async appenders. However, properties configuration is still being extensively used. Often you don’t need many of the more advanced logging features of Log4J 2. So you’re fine using the simplicity of the properties file configuration.In future posts, I will cover using other configuration options for Log4J 2 to address logging configurations with more complex requirements.

Log4J 2 Configuration: Using the Properties File - DZone (2024)

References

Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5830

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.