1

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.

ramazan polat
  • 7,111
  • 1
  • 48
  • 76

1 Answers1

1

As far as I can tell from looking at the XSD from here master branch of the Log4j-config.xsd

there is nothing like this. I would like to be wrong as I need it myself.

So if it is possible than it is not in the schema.

Did you open an issue to the developers? If yes please post a link I will upvote it too.

another relevant question is here 13904481

Boris Daich
  • 2,431
  • 3
  • 23
  • 27