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>