Signup/Sign In

Log4j2 YAML Configuration File Example

Posted in Programming   LAST UPDATED: JUNE 15, 2023

    Learn Log4j2 configuration using YAML or YML file for logging in to Java Applications in this tutorial. Log4j2 with YAML configuration file provides a simple way of setting up logging in your Java application.

    We have already covered setting up Log4j2 using XML configuration, Log4j2 using JSON configuration file, and Log4j2 using Properties 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 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 YAML file

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

    We also need to add Jackson Databind and Jackson Dataformat YAML JARs to enable Log4j2 to read the YAML configuration file.

    <dependency>
    	<groupId>com.fasterxml.jackson.dataformat</groupId>
    	<artifactId>jackson-dataformat-yaml</artifactId>
    	<version>2.10.0</version>
    </dependency>
    <dependency>
    	<groupId>com.fasterxml.jackson.core</groupId>
    	<artifactId>jackson-databind</artifactId>
    	<version>2.10.0</version>
    </dependency>

    Log4j2 Configuration using YAML File

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

    Now we will create a YAML file with the name log4j2.yaml or log4j2.ym (both of these formats are the same) 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 using YAML file example

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

    Configuration:
      name: Default
      
      Appenders:
        Console:
          name: LogToConsole
          target: SYSTEM_OUT
          PatternLayout:
            pattern: "%d [%t] %-5p %c - %m%n"
      Loggers:
          Logger:
            - name: com.abhishek.log4j2
              additivity: false
              level: debug
              AppenderRef:
                - ref: LogToConsole

    In the above YAML 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 logger, log level for it and we have provided the reference of the Console appender to it.

    We have specified the Logger for a particular package, using a similar format you can add multiple Logger for different packages with different Log levels, using the same appender or different appenders.

    We can also specify one default root logger in the YAML file under Loggers, like this:

    Root:
        level: debug
        AppenderRef:
          - ref: LogToConsole

    In the pattern value, the 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 JSON configuration file, we can set up 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 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: YAML 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 YAML configuration file. Following is the YAML configuration to print logs in a file with the name app.log in the logs folder.

    Configuration:
      name: Default
      Properties:
        Property:
          name: log-path
          value: "logs"
      
      Appenders:
        File:
          name: LogToFile
          fileName: ${log-path}/app.log
          PatternLayout:
            pattern: "%d [%t] %-5p %c - %m%n"
      Loggers:
          Logger:
            - name: com.abhishek.log4j2
              additivity: false
              level: debug
              AppenderRef:
                - ref: LogToFile

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

    We have also used the Properties section to define properties in the YAML configuration file. This is a good practice to have all the properties defined in one place at the beginning and use them in your YAML configuration file.

    But sometimes due to the amount 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 this problem we can use the RollingFile Appender.

    Log4j2 RollingFile Appender: YAML 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 of size related policy, for example, creating 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 YAML configuration for using RollingFile appender.

    Configuration:
      name: Default
      Properties:
        Property:
          name: log-path
          value: "logs"
      
      Appenders:
        RollingFile:
          - name: LogToRollingFile
            fileName: ${log-path}/app.log
            filePattern: "logs/archive/approllingfile.log.%d{yyyy-MM-dd-hh-mm}.gz"
            PatternLayout:
              pattern: "%d [%t] %-5p %c - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: 1 KB
            DefaultRollOverStrategy:
              max: 30
      Loggers:
          Logger:
            - name: com.abhishek.log4j2
              additivity: false
              level: debug
              AppenderRef:
                - ref: LogToRollingFile

    In the above YAML 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. Also, we have specified the default rollover strategy with a max value of 30, which means after 30 log lines, the rollover will be executed and an archive file will get created. You can adjust these values as per your requirements.

    The default file will be created with the name app.log while backups will be created in the archive folder in the following format: approllingfile.log.2020-04-18-09-31.gz

    Conclusion

    The Log4j2 YAML configuration file format presents a modern and streamlined approach to configuring the logging behavior of your Java applications. With its readable syntax and powerful customization options, the YAML format offers a user-friendly alternative to the traditional XML-based configuration.

    By following the example provided in this article, you can gain a deeper understanding of the YAML configuration file's structure and leverage its capabilities to fine-tune your logging configuration. Whether you prefer a more concise and visually appealing configuration or seek to simplify your logging setup, Log4j2 YAML configuration files are here to elevate your logging experience.

    Frequently Asked Questions(FAQs)

    1. What is Log4j2?

    Log4j2 is a popular logging framework for Java applications. It provides efficient and flexible logging capabilities, allowing developers to gather valuable information about their application's behavior and diagnose issues effectively.

    2. What is a Log4j2 YAML configuration file?

    A Log4j2 YAML configuration file is an alternative to the traditional XML-based configuration format. It uses YAML syntax, a human-readable and structured format, to define the logging configuration for Log4j2.

    3. Why should I use a YAML configuration file for Log4j2?

    Using a YAML configuration file for Log4j2 offers several benefits. YAML syntax is more readable and compact compared to XML, making it easier to understand and maintain logging configurations. Additionally, YAML files can be structured hierarchically, allowing for more intuitive and organized configuration setups.

    4. How do I create a Log4j2 YAML configuration file?

    To create a Log4j2 YAML configuration file, you can create a new file with the .yaml or .yml extension and define the logging configuration using YAML syntax. The file should include properties such as loggers, appenders, and log levels, which determine the behavior of Log4j2.

    5. Can I use both XML and YAML configuration files with Log4j2?

    Yes, Log4j2 supports both XML and YAML configuration files. You can choose the format that suits your preferences and requirements. However, it's important to note that using multiple configuration files simultaneously may lead to conflicts, so it's recommended to stick to a single format for consistency.

    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:log4j2
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS