Question

Is it possible to define a (named) PatternLayout within a log4j2.xml configuration file?

<?xml version="1.0" encoding="UTF-8"?>
  <configuration status="ERROR">
    <appenders>
      <Console name="CONSOLE" target="SYSTEM_OUT">
        <PatternLayout pattern="%d %-5p %C{2} (%F:%L) - %m%n" />
      </Console>

      <File name="DEBUG_FILE" fileName="debug.txt">
        <PatternLayout pattern="%d %-5p %C{2} (%F:%L) - %m%n" />
      </File>
    </appenders>

    <loggers>
      <root level="trace">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="DEBUG_FILE" />
      </root>
    </loggers> 

</configuration>

In this example the PatternLayout is repeated. Could I define it somehow globally with a name, and then just use the name reference to set the pattern for each appender?

Was it helpful?

Solution 2

Found it:

define:

    <Properties>
        <property name="path">c:/logs/</property>
    </Properties>

use:

   <RollingFile fileName="${path}mylog.log"

OTHER TIPS

According to the official documentation, you can define a "property" and reuse its value.

In this case, I am defining the appenderPatternLayout property.

Here the full code (tested with Log4J 2.3) :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>

    <Properties>
        <Property name="appenderPatternLayout">%d %-5p %C{2} (%F:%L) - %m%n</Property>
    </Properties>

    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="${appenderPatternLayout}" />
        </Console>
        <File name="DEBUG_FILE" fileName="debug.txt">
            <PatternLayout pattern="${appenderPatternLayout}" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="trace">
            <AppenderRef ref="CONSOLE" />
            <AppenderRef ref="DEBUG_FILE" />
        </Root>
    </Loggers> 
</Configuration>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top