Signup/Sign In

Log4j2 Configuration using Properties File

Posted in Programming   LAST UPDATED: JUNE 7, 2023

    Are you confused about how to use a properties file to configure your Log4j2 logger to use it in Java Application? Then this article will help you out.

    Using a properties file for Log4j2 configuration 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 files in our previous posts, you can check them out too.

    Log4j2 Properties File Example

    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 set up 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 the name of the project and as the package name for the Java project.

    Note: If you know how to set up 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 Maven Dependency in POM.xml

    To set up log4j2 for logging we will need log4j2 dependencies, which we will provide in our project's pom.xml file. Add the below code to 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 to it.

    Log4j2 Configuration using Properties File

    • We will start by creating a Properties file to define the basic configurations for log4j.

    • The properties will specify which appender to use Console appender, File appended, etc., and other settings like Pattern, log level, etc.

    So let's create a properties file.

    1. Create a Properties file with the name log4j2.properties and put it in the classpath.

    2. Log4j2 automatically looks for configuration files in the classpath.

    3. 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 file example

    Now create a new file in this source folder with the 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, and log level for it and we have provided the reference of the Console appender to it.

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

    1. %d is used to add the timestamp

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

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

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

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

    Using this Properties configuration file, you can set up basic logging in your Java class.

    Main Java Class code

    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 the 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 the 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 the 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 in the code above, we have provided the filename and a pattern just like the console appender example above.

    • Run the Java class again to check if 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 number of 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 analyze the logs.

    • To solve the large log file size problem you 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 on when to create a new file.

    • This can either be a time-related rule/policy or size related policy.

    • For example, creating a new log file every day or every hour or creating a new log file once the size reaches say 10MB or 5MB.

    Use the following Properties configuration for using the 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 the name app.log while backups will be created in the following format: app.log-backup-04-16-20-21-49-09.log

    Wrapping Up

    In this tutorial, we set up Log4j2 using the POM.xml and then learned how to do Log4j3 configuration using the Properties file. We saw how we can use Log4j2 with Java code to print logs on the console by configuring it using a Properties configuration file, in a log file, or even creating a rolling file for capturing logs from our Java application.

    Frequently Asked Questions

    Here are some frequently asked questions regarding Log4j2 logging and configuration.

    1. What exactly is Log4j2?

    Log4j2 is a logging library for Java applications, used to log events, errors, and other messages.

    2. What is a properties file in the Log4j2 configuration?

    A properties file is a configuration file used to specify the settings for Log4j2, such as log levels and output destinations.

    3. How do I configure Log4j2 using a properties file?

    Create a properties file with the desired settings, place it in the classpath, and specify the file location in the Log4j2 configuration.

    4. What are some common properties in Log4j2 configuration?

    Some common properties include log levels, output formats, output destinations, and filters to control which messages are logged.

    You may also like:

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:howtojavalog4j2
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS