logback配置中變量和include的應用方式

logback配置中變量和include的應用

logback配置在實際應用中往往會遇到appender的配置中存在大量的重復內容,但是logback又不像編程語言一樣支持繼承,采用include和變量結合可以一定程度上解決這個問題。

Example:

    <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name=WarnLogFile">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{dd.MMM.yyyy HH:mm:ss.SSS z}, [%6t], %6p, %C:%M %m%n</pattern>
        </encoder>
        <file>${LOGS_DIR}/warn.log</file>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>40MB</maxFileSize>
        </triggeringPolicy>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${LOGS_DIR}/warn%i.log.gz</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>21</maxIndex>
        </rollingPolicy>
    </appender>
    <appender class="ch.qos.logback.classic.AsyncAppender" name="Warn">
        <queueSize>2048</queueSize>
        <includeCallerData>true</includeCallerData>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="WarnLogFile" />
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>WARN</level>
        </filter>
    </appender>
    <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="InfoLogFile">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{dd.MMM.yyyy HH:mm:ss.SSS z}, [%6t], %6p, %C:%M %m%n</pattern>
        </encoder>
        <file>${LOGS_DIR}/info.log</file>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>10MB</maxFileSize>
        </triggeringPolicy>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${LOGS_DIR}/info%i.log.gz</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>21</maxIndex>
        </rollingPolicy>
    </appender>
    <appender class="ch.qos.logback.classic.AsyncAppender" name="info">
        <queueSize>2048</queueSize>
        <includeCallerData>true</includeCallerData>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="infoLogFile" />
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>
    <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="DebugLogFile">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{dd.MMM.yyyy HH:mm:ss.SSS z}, [%6t], %6p, %C:%M %m%n</pattern>
        </encoder>
        <file>${LOGS_DIR}/debug.log</file>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${LOGS_DIR}/debug%i.log.gz</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>21</maxIndex>
        </rollingPolicy>
    </appender>
    <appender class="ch.qos.logback.classic.AsyncAppender" name="Debug">
        <queueSize>2048</queueSize>
        <includeCallerData>true</includeCallerData>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="DebugLogFile" />
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
    </appender>

可以看到以上的三個定義存在大量的重復內容會導致logback文件很大,不容易維護,結合變量和include則可以一定程度上解決這個問題。

首先把配置內容抽取一個公共文件default.xml

把不同的內容用變量定義:

<included>
    <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="${FILE_APPENDER}">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{dd.MMM.yyyy HH:mm:ss.SSS z}, [%6t], %6p, %C:%M %m%n</pattern>
        </encoder>
        <file>${LOGS_DIR}/${LOGFILE}.log</file>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${LOGS_DIR}/${LOGFILE}%i.log.gz</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>21</maxIndex>
        </rollingPolicy>
    </appender>
    <appender class="ch.qos.logback.classic.AsyncAppender" name="${ASYNC_APPENDER}">
        <queueSize>2048</queueSize>
        <includeCallerData>true</includeCallerData>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="${FILE_APPENDER}" />
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>${LOG_LEVEL}</level>
        </filter>
    </appender>
</included>

然後基於公共文件定義各自的配置

warn.xml:

<included>
    <property scope="local" name="LOGFILE" value="warn" />
    <property scope="local" name="FILE_APPENDER" value="WarnLogFile" />
    <property scope="local" name="ASYNC_APPENDER" value="warn" />
    <property scope="local" name="LOG_LEVEL" value="WARN" />
    
    <include file="${LOGS_CUSTOM_DIR}/default.xml"/>
</included>

info.xml:

<included>
    <property scope="local" name="LOGFILE" value="info" />
    <property scope="local" name="FILE_APPENDER" value="InfoLogFile" />
    <property scope="local" name="ASYNC_APPENDER" value="info" />
    <property scope="local" name="LOG_LEVEL" value="INFO" />
    
    <include file="${LOGS_CUSTOM_DIR}/default.xml"/>
</included>

debug.xml:

<included>
    <property scope="local" name="LOGFILE" value="debug" />
    <property scope="local" name="FILE_APPENDER" value="DebugLogFile" />
    <property scope="local" name="ASYNC_APPENDER" value="debug" />
    <property scope="local" name="LOG_LEVEL" value="DEBUG" />
    
    <include file="${LOGS_CUSTOM_DIR}/default.xml"/>
</included>

最後在logback.xml中就可以include上面定義的文件

    <include file="${LOGS_CUSTOM_DIR}/warn.xml"/>
    <include file="${LOGS_CUSTOM_DIR}/info.xml"/>
    <include file="${LOGS_CUSTOM_DIR}/debug.xml"/>
    <root level="DEBUG">
        ...
        <appender-ref ref="warn"/>
        <appender-ref ref="info"/>
        <appender-ref ref="debug"/>
    </root>

logback.xml導入(include)其他項目配置的logback.xml文件

1、其他項目存在的logback.xml文件需要下面這種形式的配置 ​

下面的這個配置文件的意思是定義瞭兩個appender,這兩個appender中名為ASYNC-LOG的appender是將com.xx.cloud.trail.client.async路徑下面產生的級別為error的日志進行收集,保存在定義的文件夾下面,另一個appender同理,如果這個logback.xml文件想在其他的項目中被引用那麼就需要用在iucluded標簽將定義的appender跟logger包圍起來,表示這個是可以被導入其他項目的

<?xml version="1.0" encoding="UTF-8"?>
    <included>
    <appender name="ASYNC_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件輸出的文件名-->
            <FileNamePattern>/var/log/xx/cloud/trail/async/error.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder
                class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <!-- 日志輸出編碼 -->
            <layout class="ch.qos.logback.classic.PatternLayout">
                <!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日志消息,%n是換行符-->
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
                </pattern>
            </layout>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <appender name="AOP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件輸出的文件名-->
            <FileNamePattern>/var/log/xx/cloud/trail/aop/error.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder
                class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <!-- 日志輸出編碼 -->
            <layout class="ch.qos.logback.classic.PatternLayout">
                <!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日志消息,%n是換行符-->
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
                </pattern>
            </layout>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!--需要將日志單獨輸出的包路徑-->
    <logger name="com.xx.cloud.trail.client.async" level="ERROR" additivity="false">
        <appender-ref ref="ASYNC_LOG"/>
    </logger>
    <!--需要將日志單獨輸出的包路徑-->
    <logger name="com.xx.cloud.trail.client.aop" level="ERROR" additivity="false">
        <appender-ref ref="AOP_LOG"/>
    </logger>
    </included>

2、其他項目的配置

假如1中的配置logback.xml文件的名稱為logback-trail.xml,那麼需要在其他的項目的logback.xml文件中加入一句

表示導入其他項目的logback文件,這樣就能將其他項目中的配置文件進行導入

<?xml version="1.0" encoding="UTF-8"?>
<!--
    scan: 當此屬性設置為true時,配置文件如果發生改變,將會被重新加載,默認值為true。
    scanPeriod: 設置監測配置文件是否有修改的時間間隔,如果沒有給出時間單位,默認單位是毫秒。當scan為true時,此屬性生效。默認的時間間隔為1分鐘。
    debug: 當此屬性設置為true時,將打印出logback內部日志信息,實時查看logback運行狀態。默認值為false。
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <include resource="logback-trail.xml"/>
    <!--配置日志輸出到的路徑-->
    <springProperty scop="context" name="logging.path" source="logging.path"
                    defaultValue="logging-path-not-find"/>
    <property name="log.path" value="${logging.path}"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="TRAIL_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件輸出的文件名-->
            <FileNamePattern>${logging.path}/trail/trail.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder
                class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <!-- 日志輸出編碼 -->
            <layout class="ch.qos.logback.classic.PatternLayout">
                <!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日志消息,%n是換行符-->
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
                </pattern>
            </layout>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!-- 日志輸出級別 -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="TRAIL_LOG"/>
    </root>
</configuration>

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: