Examples of log4j2.xml configuration and differences from log4j

Keywords: Java log4j xml encoding Attribute

<?xml version="1.0" encoding="UTF-8" ?>
<configuration status="warn">

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%p] %d %c %l - %m%n"/>
        </Console>

        <RollingFile name="activity" fileName="/opt/fox.log"
                     filePattern="/opt/fox.log.%d{yyyy-MM-dd}.gz">
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
            <PatternLayout pattern="[%p] %d - %m%n" charset="UTF-8"/>
        </RollingFile>
        <RollingFile name="fox_err" fileName="/opt/fox_err.log"
                     filePattern="/opt/fox_err..log.%d{yyyy-MM-dd}.gz">
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
            <PatternLayout pattern="[%p] %d %l - %m%n" charset="UTF-8"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <logger name="com.fox" additivity="false" level="info">
            <appender-ref ref="activity" />
            <appender-ref ref="activity_err" level="error"/>
        </logger>
        <Root level="error">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>

</configuration>

Compared with log4j, there are some major changes.

Firstly, the whole structure changes greatly, appender and logger are concentrated under one root node.

The names of nodes in xml have also adopted a new design. Names are directly useful information. They are no longer appender XXX = "xxx" and param XXX = "xxx".

Then some attributes, including fileName, can only be configured as node attributes, not as sub-nodes as log4j.

In addition, log4j2 supports compression when archiving. File name suffixes are written into gz,zip and other compression formats in the filePattern s attribute of RollingFile node. Log4j2 will automatically select the corresponding compression algorithm for compression.

That's all we've found now. By introducing this xml configuration and referring to the log4j-core, log4j-api package, we can use log4j2. In addition, if necessary, we can use log4j-slf4j-impl, log4j-jcl, log4j-1.2-api to achieve compatibility with slf4j, JCL and log4j, respectively.

Posted by Pr0digy on Thu, 14 Feb 2019 07:27:19 -0800