New Tutorials:   JAVASCRIPT    SASS/SCSS    PL/SQL  
   Log4j2  Java  Logging  
   Technology    Programming

Log4j2 JSONLayout - Adding Custom KeyValuePair Fields

 MAY 13, 2020   by iamabhishek

In Log4j2, adding custom key-value pair enables you to add custom fields while publishing logs in JSON format. We have already covered how to configure Log4j2 using various different configuration files and to print logs in different patterns like JSON, etc.

Log4j2 with XML Configuration File Example

Log4j2 setup with Configuration in JSON File

Log4j2 Configuration with Properties File

Log4j2 YAML Configuration File Example

Adding Custom KeyValuePair using Properties Configuration

If you want to configure additional field using properties file or programmatically using Java code, following proeprties can be used:

appender.Console.layout.additionalField1.type = KeyValuePair
appender.Console.layout.additionalField1.key = StudytonightCustomKey
appender.Console.layout.additionalField1.value = StudytonightCustomValue

Similarly, you can add multiple custom fields,

appender.Console.layout.additionalField2.type = KeyValuePair
appender.Console.layout.additionalField2.key = StudytonightCustomKey
appender.Console.layout.additionalField2.value = StudytonightCustomValue

To configure Log4j2 to add custom fields programmatically, create a Properties object, set the above properties in it, and then we can create org.apache.logging.log4j.core.config.ConfigurationSource using the following properties object, which can be used to reconfigure the log4j2 logger.

Properties cfg = new Properties();

cfg.setProperty("", "StudytonightLogger");
cfg.setProperty("appender.myAppender.layout.type", "JSONLayout");
cfg.setProperty("appender.myAppender.layout.compact", "true");
cfg.setProperty("appender.myAppender.layout.complete", "false");
cfg.setProperty("appender.myAppender.layout.additionalField1.type", "KeyValuePair");
cfg.setProperty("appender.myAppender.layout.additionalField1.key", "StudytonightCustomKey");
cfg.setProperty("appender.myAppender.layout.additionalField1.value", "StudytonightCustomValue");

Adding Custom KeyValuePair using XML Configuration

If you are using XML file to configure the log4j2, you can do so like this:

<Configuration status="WARN">
        <Console name="LogInJSON" target="SYSTEM_OUT">
        	<JsonLayout complete="false" compact="false">
                <!-- Custom key value pair -->
            	<KeyValuePair key="StudytonightField" value="studytonightValue" />
        <Logger name="com.abhishek.log4j2" level="debug" additivity="false">
            <AppenderRef ref="LogInJSON"/>
        <Root level="error">
            <AppenderRef ref="LogInJSON"/>

Hope this tutorial helps you in configuring the log4j2 logger to print logs in JSON Layout along with custom key value pairs. If you have any doubt, feel free to comment.


Subscribe and receive amazing posts directly in your inbox.