Technology6 min read

Log4j2 Configuration using Properties File

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

Learn Log4j2 setup with configuration in Properties file for logging in Java Application in this tutorial. Log4j2 with Properties configuration file provides a simple way of setting up logging in your Java application.

We have already covered setting up Log4j2 using XML configuration and Log4j2 using JSON configuration file in our previous posts.

Apache Log4j2 is the new version of the log4j and is used for printing logs when used in a Java program. In this tutorial we will setup a Maven project and use log4j2 to print logs from a simple Java class.

If you are using Eclipse IDE, click on File > New > Project > Maven Project (You must have Maven Plugin installed in Eclipse for this)

When asked for Group Id and Artifact Id, enter what you want, this will be used as name of the project and as package name for the Java project.

Note: If you know how to setup a Maven Project, do it yourself.

Once you are done, you should have a project structure similar to this,

Log4j2 configuration using Properties file

Log4j2 Dependency in POM.xml

To setup log4j2 for logging we will need log4j2 dependencies, which we will provide in our project's pom.xml file. Add the below code into your pom.xml file:

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

The above code should be enclosed within the <dependencies> tag, if existing, add the above code to it, else create an opening and closing <dependencies> tag and add the above code in it.

Log4j2 Configuration using Properties File

We will create a Properties file to define the basic configurations for log4j like which appender to use Console appender, File appender etc and other setting like Pattern, log level etc.

Now we will create a Properties file with name log4j2.properties and put it in the classpath, Log4j2 automatically looks for configuration files in the classpath. We will keep this in src/main/resource folder.

To create this folder, right click on the project, go to New > Source Folder and provide the name src/main/resource:

log4j2 configuration in Properties file example

Now create a new file in this source folder with name log4j2.properties and add the following code to it:

status = error
name = Log4j2PropertiesConfig
 
appenders = console
 
appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d [%t] %-5p %c - %m%n
 
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = LogToConsole

In the above Properties file we have specified a Console appender with basic information like name and a pattern to be used for printing log events. Also, we have specified the default root logger, log level for it and we have provided the reference of the Console appender to it.

In the pattern value, following is the use of every component:

%d is used to add the timestamp

[%t] will add the thread name to the log statement.

%-5p will add the log level information to the log statement.

%c will add the fully qualified class name which is logging the log statement.

%msg is for the log message and %n is for adding a new line after every log statement.

Using this Properties configuration file, we can setup basic logging in our Java class.

Main Java Class

Add the following code to the main Java class:

package com.abhishek.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class App {
	
	private static final Logger logger = LogManager.getLogger(App.class);

	public static void main(String[] args) {

		logger.debug("Hello from Log4j 2");
		logger.debug("This is a Debug Message!");
		logger.info("This is an Info Message!");
		logger.error("And here comes the Error Message!", new RuntimeException("RunRunRun"));
		
	}
}

Change the code as per your project's package name etc.

Once you are done with all this, right click on the main java class which is App.java in our case and run it as a Java Application. You should get the following output in console:


2020-04-16 21:30:54,076 [main] DEBUG com.abhishek.log4j2.App - Hello from Log4j 2
2020-04-16 21:30:54,082 [main] DEBUG com.abhishek.log4j2.App - This is a Debug Message!
2020-04-16 21:30:54,082 [main] INFO com.abhishek.log4j2.App - This is an Info Message!
2020-04-16 21:30:54,082 [main] ERROR com.abhishek.log4j2.App - And here comes the Error Message!
java.lang.RuntimeException: RunRunRun
at com.abhishek.log4j2.App.main(App.java:15) [classes/:?]

Log4j2 File Appender: Properties Configuration for Printing logs in File

To print logs in a file rather than printing on console, we will use File appender instead of Console appender in the Properties configuration file. Following is the Properties configuration to print logs in a file with name app.log in the logs folder.

status = error
name = Log4j2PropertiesConfig
 
appenders = file
 
appender.file.type = File
appender.file.name = FileLogger
appender.file.filename = logs/app.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = %d [%t] %-5p %c - %m%n
 
rootLogger.level = debug
rootLogger.appenderRefs = file
rootLogger.appenderRef.file.ref = FileLogger

As you can see that we have provided the filename and a pattern just like the console appender example above.

Run the Java class again to check of the log file is getting created. You can even run the Java class multiple times and the logs will be appended in the same file.

Using a File appender and storing logs in a file helps in storing the logs for later analysis.

But sometimes due to the amount of the logs being printed by an application the size of the log file can grow into MBs and even GBs, hence making it difficult for us to access and analyse the logs. To solve this problem we can use the RollingFile Appender.

Log4j2 RollingFile Appender: Properties Configuration for RollingFile

Log4j2 RollingFile appender can be used to configure the Log4j2 to create new files by setting rules when to create a new file, this can either be a time related rule/policy of size related policy, for example, create a new log file every day or every hour or create a new log file once the size reaches say 10MB or 5MB.

Use the following Properties configuration for using RollingFile appender.

status = error
name = Log4j2PropertiesConfig
 
# change log file name as per your requirement
property.filename = app.log
 
appenders = rolling
 
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = ${filename}-backup-%d{MM-dd-yy-HH-mm-ss}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d [%t] %-5p %c - %m%n
appender.rolling.policies.type = Policies
# To change log file every day
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
# To change log file after 1Kb size
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=1Kb
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
 
loggers = rolling
 
# change the package structure as per your application
 
logger.rolling.name = com.abhishek.log4j2
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile

In the above Properties configuration we have set the rolling file appender policy for size as 1 Kb just to show you how a file with old logs is created once the size exceeds 1 Kb. Ideally you should keep this value in MBs.

The default file will be created with name app.log while backups will be created in the following format: app.log-backup-04-16-20-21-49-09.log

Conclusion:

In this tutorial we saw how we can use Log4j2 with Java code to print logs on console by configuring it using a Properties configuration file, in a log file or even create rolling file for capturing logs from our Java application.

You may also like:

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next