Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a global PatternLayout for log4j2?

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?

like image 508
membersound Avatar asked Jan 07 '14 14:01

membersound


People also ask

What is PatternLayout in Log4j2?

PatternLayout to format your logging information. The PatternLayout class extends the abstract org. apache. log4j. Layout class and overrides the format() method to structure the logging information according to a supplied pattern.

How do you set a log4j properties file location?

The file is named log4j. properties and is located in the $DGRAPH_HOME/dgraph-hdfs-agent/lib directory. The file defines the ROLLINGFILE appenders for the root logger and also sets the log level for the file. The level of the root logger is defined as INFO and attaches the ROLLINGFILE appender to it.


2 Answers

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>
like image 197
Stéphane B. Avatar answered Sep 22 '22 14:09

Stéphane B.


Found it:

define:

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

use:

   <RollingFile fileName="${path}mylog.log"
like image 22
membersound Avatar answered Sep 21 '22 14:09

membersound