Log4j2 JSON Configuration Example

Apache Log4j 2 is an upgrade to Log4j 1.x that provides significant improvements over its predecessor such as performance improvement, automatic reloading of modified configuration files, Java 8 lambda support and custom log levels.

In addition to XML and properties files, Log4j2 can be configured using JSON also.

1. Log4j2 Dependencies

To include Log4j2 in the project, include below dependency.

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

The Log4j2 uses Jackson to parse the JSON files – so let’s add it’s dependencies as well.

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

2. Log4j2.json – Console Logs

You can use below src/main/resources/log4j2.json file logging output into console. Please note that if no configuration file could be located then DefaultConfiguration will be used. This also causes logging output to go to the console.

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

3. Log4j2.json – File Logs

You can use below log4j2.json file logging output into size based rolling files.

{
   "configuration": {
      "name": "Default",
      "appenders": {
         "RollingFile": {
            "name":"File",
            "fileName":"C:/logs/howtodoinjava.log",
            "filePattern":"C:/logs/howtodoinjava-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz",
            "PatternLayout": {
               "pattern":"%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"
            },
            "Policies": {
               "SizeBasedTriggeringPolicy": {
                  "size":"10 MB"
               }
            },
            "DefaultRolloverStrategy": {
               "max":"10"
            }
         }
      },
      "loggers": {
         "root": {
            "level":"debug",
            "appender-ref": {
              "ref":"File"
            }
         }
      }
   }
}

4. Log4j2.json File Location

You should put log4j2.json anywhere in application’s classpath. Log4j2 will scan all classpath locations to find out this file and then load it.

Log4j2.json file location
Log4j2.json file location

5. Demo

Let’s write a java class and write few log statements to verify that logs are appearing in console and log file as well.

package com.howtodoinjava.log4j2.examples;

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

public class Log4j2HelloWorldExample 
{
	private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample.class.getName());
	
	public static void main(String[] args) 
	{
		LOGGER.debug("Debug Message Logged !!!");
		LOGGER.info("Info Message Logged !!!");
		LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError"));
	}
}

Now when we run the above program, we will get the below logs in the console.

2016-06-16 15:06:25 DEBUG Log4j2HelloWorldExample:12 - Debug Message Logged !!!
2016-06-16 15:06:25 INFO  Log4j2HelloWorldExample:13 - Info Message Logged !!!
2016-06-16 15:06:25 ERROR Log4j2HelloWorldExample:14 - Error Message Logged !!!

java.lang.NullPointerException: NullError at com.howtodoinjava.log4j2.examples.Log4j2HelloWorldExample.main
(Log4j2HelloWorldExample.java:14) [classes/:?]

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Log4j2 JSON Configuration Example”

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.