1. 程式人生 > >關於log4j2的xml配置,以及不同級別日誌輸出到不同日誌檔案

關於log4j2的xml配置,以及不同級別日誌輸出到不同日誌檔案

例如,考慮下如下的常見場景:WEB應用,我們不希望把log4j2.xml打包到自己的jar檔案中(這樣修改log4j2的配置就麻煩了),也不希望把log4j2.xml放到WEB-INF/classes下面(不希望使用者隨便操作WEB-INF下的檔案),那我們可以把log4j2.xml和其他專案中用到的配置檔案,放到一個集中的地方,比如TOMCAT/bin/config下,這時,改如果初始化log4j2呢?我們可以提供一個InitServlet,例如:

public void init() throws ServletException {  
    String configRoot = this
.getInitParameter("configRoot"); String log4j2Config = configRoot + File.separator + this.getInitParameter("log4j2Config"); File file = new File(log4j2Config); try { LoggerContext context =(LoggerContext)LogManager.getContext(false); context.setConfigLocation(file.toURI()); //重新初始化Log4j2的配置上下文
context.reconfigure(); } catch (MalformedURLException e) { e.printStackTrace(); } //todo: 這裡拿到的logger,已經是按新配置檔案初始化的了 logger = LogManager.getLogger(DefaultInitServlet.class); }

相應的,只要在web.xml配置這個InitServlet,並提供configRoot和log4j2Config兩個路徑即可(也可以不要配置configRoot,而是通過System.getProperty(“user.dir”)來獲取應用的執行目錄,對tomcat而言,這個目錄就是tomcat/bin,其他如命令列的應用,就是bat/sh的所在目錄)
web.xml

<servlet> 
    <servlet-name>InitServlet</servlet-name> 
    <servlet-class>test.InitServlet</servlet-class> 
    <load-on-startup>0</load-on-startup> 
    <init-param> 
        <!-- 配置檔案根目錄 --> 
        <param-name>configRoot</param-name> 
        <param-value>d://config</param-value> 
    </init-param> 
    <init-param> 
        <!-- log4j2配置檔案相對路徑  --> 
        <param-name>log4j2Config</param-name> 
        <param-value>log4j2/log4j2.xml</param-value> 
    </init-param> 
</servlet> 

再講下如何把不同級別的日誌,輸出到不同的日誌檔案中。這個在網上,包括官網上,都沒有一個是說清楚的。

比如,希望trace/debug級別的日誌輸出到debug.log,而info級別的日誌輸出到info.log,其他如warn/error/fatal級別的日誌都輸出到error.log,這樣分開輸出是有好處的。我們按照如下的log42j.xml的配置,即可實現這樣的輸出。

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

<configuration debug="off" monitorInterval="1800">
    <Properties>
        <Property name="log-path">d://logs</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36}.%M()/%L  - %msg%xEx%n"/>
        </Console>

        <File name="app_debug" fileName="${log-path}/app/debug.log" append="false">
            <Filters>
                <ThresholdFilter level="info" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/>
        </File>
        <File name="app_info" fileName="${log-path}/app/info.log" append="false">
            <Filters>
                <ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>

            <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/>
        </File>
        <File name="app_error" fileName="${log-path}/app/error.log" append="false">
            <Filters>
                <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.test.app" level="trace" additivity="false">
            <appender-ref ref="Console"/>
            <appender-ref ref="app_debug"/>
            <appender-ref ref="app_info"/>
            <appender-ref ref="app_error"/>
        </Logger>
    </Loggers>
</configuration>

主要是要理解ThresholdFilter的onMatch/onMismatch的三個選項值:ACCEPT/DENY/NEUTRAL,其實,根據字面意思,也很好理解。
重要的是,如果有多個ThresholdFilter,那麼Filters是必須的,同時在Filters中,首先要過濾更高級別的,將其NEUTRAL交給下一個高級別的過濾器處理, 不符合的日誌級別,把不需要的DENY掉,然後再ACCEPT需要的日誌級別,這個次序不能搞顛倒。