HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Log4j2 / Log4j 2 JSON Configuration Example

Log4j 2 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, Log4j can be configured using JSON also.

Log4j2 dependencies

To include Log4j2 in your project, include below dependency in your project.

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

log4j2.json for Console logging

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"
                }
            }
        }
    }
}

log4j2.json for logging into rolling files

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"
            }
         }
      }
   }
}

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

log4j2.json example

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 you run the above program, you will get below logs in 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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. R.Marie

    April 13, 2020

    this website is awesome !

  2. uday

    February 24, 2020

    simple explanation

  3. Mondlane

    January 25, 2020

    Simple explanation and easy to read

  4. andrew krenitz

    January 15, 2019

    This worked. I am using this is a web application to log requests. Thanks for the post.

Comments are closed on this article!

Search Tutorials

Log4j2 Tutorial

  • Log4j2 – Introduction
  • Log4j2 – JSON Config
  • Log4j2 – Properties Config
  • Log4j2 – XML Config
  • Log4j2 – RollingFileAppender
  • Log4j2 – Multiple appenders
  • Log4j2 – LevelRangeFilter
  • Log4j2 – HTMLLayout
  • Log4j2 – Fish Tagging
  • Log4j2 – Conversion Patterns
  • Log4j2 – JUnit

Log4j Tutorial

  • Log4j – Introduction
  • Log4j – Properties Config
  • Log4j – XML Config
  • Log4j – Maven Config
  • Log4j – Logging Levels
  • Log4j – ConsoleAppender
  • Log4j – RollingFileAppender
  • Log4j – SocketAppender
  • Log4j – JDBCAppender
  • Log4j – XMLLayout
  • Log4j – HTMLLayout
  • Log4j – Runtime Reload
  • Log4j vs. SLF4j
  • Log4j – RESTEasy + Tomcat 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces