Log4j2 File Inclusion : and s

2019-07-04 11:22发布

问题:

Does Log4j2 support file inclusion mechanism like Logback does ? This is for including parts of a configuration file from another file (containing appenders, loggers etc.)

As an FYI - Here is how it works in Logback:

Joran supports including parts of a configuration file from another file. This is done by declaring a element, as shown below:

Example: File include (logback-examples/src/main/java/chapters/configuration/containingConfig.xml)

<configuration>
<include file="src/main/java/chapters/configuration/includedConfig.xml"/>

<root level="DEBUG">
<appender-ref ref="includedConsole" />
</root>

The target file MUST have its elements nested inside an element. For example, a ConsoleAppender could be declared as:

Example: File include (logback-examples/src/main/java/chapters/configuration/includedConfig.xml)

<included>
<appender name="includedConsole" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
  <pattern>"%d - %m%n"</pattern>
</encoder>
</appender>
</included>

回答1:

XInclude can be used, but isn't an ideal solution. When using XInclude the include files themselves have to define a single top level element such as Appenders/Loggers/Properties.

Here's an example of how you could use it:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" xmlns:xi="http://www.w3.org/2001/XInclude">
    <!-- this will override the log pattern defined in the included log4j-properties.xml -->
    <Properties>
        <Property name="log-pattern">jit %d %-5p [%t] %C{1.} - %m%n</Property>
    </Properties>

    <xi:include href="log4j2-properties.xml" />
    <xi:include href="log4j2-appenders.xml" />
    <xi:include href="log4j2-loggers.xml" />
</Configuration>

As an example include the log4j2-properties.xml could look like:

<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <!-- define the log pattern as a property so that it can be overridden -->
    <Property name="log-pattern">%d %-5p [%t] %C{1.} - %m%n</Property>
</Properties>

You can make XIncludes optional by using an empty "fallback" block. However in the latest version of log4j2 that is available this results in a warning message coming out of Xerces (since the DefaultErrorHandler is being used by log4j2).

<xi:include href="log4j2-optional.xml">
    <xi:fallback />
</xi:include>


回答2:

A slightly different but similar mechanism exists in Log4j2, it supports XInclude. See https://issues.apache.org/jira/browse/LOG4J2-341 for details. (This needs to be documented better...)