We can define an appender and set it for multiple loggers by referencing it with AppenderRef
.
So is it possible to have a global Layout
and reference it in any appender we want?
Just like AppenderRef
in an Appender
, can we use LayoutRef
in a Layout
?
Something like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<Property name="env">dev</Property>
<Property name="app">MyApp</Property>
<Property name="module">MyModule</Property>
<Lots Of Other Properties/>
</Properties>
<Layouts>
<JsonLayout name="MyJsonLayout" complete="false" compact="false">
<KeyValuePair key="myKey" value="myValue" />
<KeyValuePair key="app" value="${app}"/>
<KeyValuePair key="module" value="${module}"/>
<KeyValuePair key="env" value="${env}"/>
<Lots Of Other reference to properties/>
</JsonLayout>
</Layouts>
<Appenders>
<Console name="consoleJson" target="SYSTEM_OUT">
<LayoutRef ref="MyJsonLayout"/>
</Console>
<Kafka name="kafkaJson" topic="myTopic">
<LayoutRef ref="MyJsonLayout"/>
</Console>
</Appenders>
<Loggers>
<Logger name="class1" level="debug">
<AppenderRef ref="kafkaJson"/>
</Logger>
<Logger name="class2" level="debug">
<AppenderRef ref="kafkaJson"/>
</Logger>
<Root level="error">
<AppenderRef ref="consoleJson"/>
</Root>
</Loggers>
Why I need this?
I've certain properties set at the beginning of my log4j2.xml
config file and I'm using those properties in the JsonLayout as you can see them named as app
, module
, etc. By defining a global Layout, I'll have the luxury to edit the Properties
part only. Otherwise, I need to make my changes in all appenders because they will have their own Layout and all properties of the layouts will be the same. It will be inefficient to have to write the same layout to different appenders.