XML 配置

XML 示例

以下配置配置两个 appender(日志输出)。第一个记录到标准系统输出(控制台),其他记录到文件。在此示例中,文件的位置可以在配置(appender file)中静态设置,也可以通过 maven 过滤功能(<Property name="APPENDER">)动态设置。日志文件将按天打包。日志行格式 Conversion Pattern 设置为变量。

<?xml version="1.0" encoding="UTF-8"?>
<!-- 'status' sets log level for parsing configuration file itself -->
<Configuration status="INFO">
<Properties>
    <!-- Sets variable PID, if it's not present in log4j context will take value as below: -->
    <Property name="PID">????</Property>
    <!-- Sets variable 'LOG_PATTERN', defining how log line will look like -->
    <Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{%X{usr}}{green} %clr{---}{faint}%clr{[%15.15t]}{faint} %clr{%-40.40c{1.}:%l}{cyan} %clr{:}{faint} %m%n%wEx</Property>
    <!-- LOG_DIR may be set by maven filtering feature: -->
    <Property name="LOG_DIR">@logging.path@</Property>
    <!-- APPENDER may be set by maven filtering feature, to set 'console' or 'file' appender: -->
    <Property name="APPENDER">@logging.default.appender@</Property>
</Properties>
<Appenders>
    <!-- Sets console output: -->
    <Console name="console" target="SYSTEM_OUT">
        <PatternLayout pattern="${LOG_PATTERN}"/>
    </Console>
    <!-- Sets output to file, and names it 'file' -->
    <RollingRandomAccessFile append="true" fileName="${LOG_DIR}/log4j2.log"
        filePattern = "${LOG_DIR}/log4j2.%d{yyyy-MM-dd}.nr%i.log.gz" name="file">
        <PatternLayout>
            <Pattern>${LOG_PATTERN}</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy />
        </Policies>
    </RollingRandomAccessFile>
</Appenders>
<Loggers>
    <!-- Sets debug for Class 'com.example.package.Clazz', and attaches to file 'file' -->
    <Logger name="com.example.package.Clazz" level="debug">
        <AppenderRef ref="file"/>
    </Logger>
    <!-- Sets 'info' for package 'org.springframework' -->
    <Logger name="org.springframework" level="info" />
    <Root level="WARN">
        <AppenderRef ref="${APPENDER}"/>
    </Root>
</Loggers>
</Configuration>