Signup/Sign In

Log4j2 Setup with Configuration in JSON File - Java Example

Posted in Programming   LAST UPDATED: AUGUST 30, 2021

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

    We have already covered setting up Log4j2 using XML configuration in one of our previous post.

    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,

    Using log4j2 for logging in Java

    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.

    Along with the above dependency, Log4j2 also requires Jackson Jars to parse the JSON configuration file, so we will have to add the following dependecies too in the pom.xml file:

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

    Log4j2 JSON Configuration File

    We will create a JSON 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 JSON file with name log4j2.json 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 example with JSON configuration

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

    {
        "configuration": {
            "status": "error",
            "name": "Log4j2JSONConfig",
            "packages": "com.abhishek.log4j2",
            "appenders": {
                "Console": {
                    "name": "STDOUT",
                    "PatternLayout": {
                        "pattern": "%d [%t] %-5p %c - %m%n"
                    }
                }
            },
            "loggers": {
                "root": {
                    "level": "debug",
                    "AppenderRef": {
                        "ref": "STDOUT"
                    }
                }
            }
        }
    }

    In the above JSON 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 JSON 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 08:15:56,309 [main] DEBUG com.abhishek.log4j2.App - Hello from Log4j 2
    2020-04-16 08:15:56,312 [main] DEBUG com.abhishek.log4j2.App - This is a Debug Message!
    2020-04-16 08:15:56,312 [main] INFO com.abhishek.log4j2.App - This is an Info Message!
    2020-04-16 08:15:56,312 [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: JSON 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 JSON configuration file. Following is the JSON configuration to print logs in a file with name app.log in the logs folder.

    {
        "configuration": {
            "status": "error",
            "name": "Log4j2JSONConfig",
            "packages": "com.abhishek.log4j2",
            "appenders": {
                "File": {
                    "name": "FileLogger",
                    "filename": "logs/app.log",
                    "PatternLayout": {
                        "pattern": "%d [%t] %-5p %c - %m%n"
                    }
                }
            },
            "loggers": {
                "root": {
                    "level": "debug",
                    "AppenderRef": {
                        "ref": "FileLogger"
                    }
                }
            }
        }
    }

    As you can see that we have provided the filename and a pattern just like the console appender example above. We have also changes the value of the ref attribute in the AppenderRef key in the root key in loggers.

    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: JSON 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 JSON configuration for using RollingFile appender.

    {
        "configuration": {
            "status": "error",
            "name": "Log4j2JSONConfig",
            "packages": "com.abhishek.log4j2",
            "appenders": {
                "RollingFile": {
                    "name": "RollingFileLogger",
                    "filename": "logs/app.log",
                    "filePattern": "app-%d{yyyy-MM-dd}.log",
                    "PatternLayout": {
                        "pattern": "%d [%t] %-5p %c - %m%n"
                    },
                    "Policies": {
                    	"TimeBasedTriggeringPolicy": {
                    		"interval": "1", 
                    		"modulate": "true"
                    	},
                    	"SizeBasedTriggeringPolicy": {
                    		"size": "1 Kb"
                    	}
                    }
                }
            },
            "loggers": {
                "root": {
                    "level": "debug",
                    "AppenderRef": {
                        "ref": "RollingFileLogger"
                    }
                }
            }
        }
    }

    In the above JSON 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.

    Conclusion:

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

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

    RELATED POSTS