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("appender.myAppender.type","File");
cfg.setProperty("appender.myAppender.name", "StudytonightLogger");
cfg.setProperty("appender.myAppender.fileName","app.log");
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">
<Appenders>
<Console name="LogInJSON" target="SYSTEM_OUT">
<JsonLayout complete="false" compact="false">
<!-- Custom key value pair -->
<KeyValuePair key="StudytonightField" value="studytonightValue" />
</JsonLayout>
</Console>
</Appenders>
<Loggers>
<Logger name="com.abhishek.log4j2" level="debug" additivity="false">
<AppenderRef ref="LogInJSON"/>
</Logger>
<Root level="error">
<AppenderRef ref="LogInJSON"/>
</Root>
</Loggers>
</Configuration>
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.