The logback manual #03# Configuration

(粗糙選譯。。)html

Joran是logback所依賴的配置框架。java

Configuration in logback

觀察代表,在一個應用程序中,日誌代碼大概佔4%左右。node

因此即使是一個幾千行。。幾萬行的程序也有成百上千的日誌語句,鑑於它們的數量,咱們須要工具來管理這些日誌語句。logback既能夠經過編程方式配置,也能夠經過腳本配置(XML或Groovy 格式)。順便說一下,現有的log4j用戶可使用PropertiesTranslator 應用程序將log4j.properties轉換爲logback.xmlapache

讓咱們從討論logback嘗試配置自身的初始化步驟開始:編程

  1. Logback嘗試在classpath中查找一個名爲logback-test.xml的文件。
  2. 若是沒找到,logback將嘗試在classpath中檢查有沒有logback.groovy
  3. 若是仍是沒有找到,logback繼續在classpath中找logback.xml
  4. 若是依然沒找到,則使用service-provider loading facility(JDK 1.6中引入的)經過查找類路徑中的文件META-INF\services\ch.qos.logback.classic.spi.Configurator來解析com.qos.logback.classic.spi.Configurator接口的實現。它的內容應該指定所需Configurator實現的徹底限定類名。
  5. 若是以上方法都不成功,logback將使用BasicConfigurator自動配置本身,這將致使日誌輸出定向到控制檯。

Automatically configuring logback

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.sample.logback</groupId>
    <artifactId>test-logback</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- -source 1.5 中不支持 try-with-resources-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--Failed to load class "org.slf4j.impl.StaticLoggerBinder".-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
</project>
pom.xml

BasicConfigurator是logback默認的一個最小可用的配置。試了下文檔裏的例子程序,在main函數裏跑,debug信息莫名奇妙輸不出來(只輸出info的),但在junit裏跑卻又能夠。。api

Automatic configuration with logback-test.xml or logback.xml

和沒有xml文件時的默認配置等價的最小可用xml配置:oracle

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

Automatic printing of status messages in case of warning or errors

啓用「觀察logback內部狀態模式」(若是logback出現內部錯誤則不啓用也會自動輸出到控制檯):app

        // assume SLF4J is bound to logback in the current environment
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        // print logback's internal status
        StatusPrinter.print(lc);

Status data

啓用「觀察logback內部狀態模式」一般對診斷logback問題大有幫助。所以,強烈建議將其視爲第一求助辦法。(通常狀況都是推薦啓用的。)xml啓用「觀察logback內部狀態模式」:框架

<configuration debug="true"> 

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
    <!-- encoders are  by default assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

等價寫法:maven

<configuration>
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />  

  ... the rest of the configuration file  
</configuration>

Automatically reloading configuration file upon modification

30秒(默認單位是毫秒)掃描一次,若是文件改變就自動從新配置:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

在編輯xml的時候很容易出錯,因此感受不是很好用。

Enabling packaging data in stack traces

Viewing status messages

經過網頁來查看logback的內部狀態信息。

Listening to status messages

"logback.statusListenerClass" system property

Stopping logback-classic

Configuration file syntax

Example1- 關於logger、root、appender元素的一些基本知識

<configuration debug="true">
    <!--一個可選的元素,便於區分不一樣程序的輸出-->
    <contextName>myapp</contextName>

    <!--配置appender元素:
        一、name和class是必要的
        二、一個appender能夠包含零到多個layout元素
        三、一個appender能夠包含零到多個encoder元素
        四、一個appender能夠包含零到多個filter元素
        五、除了這三個公共元素以外,<appender>元素能夠包含與appender類的JavaBean屬性相對應的任意數量的元素。
        -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>myApp.log</file>
        <encoder>
            <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 配置logger元素:
        一、name是必要的
        二、level是可選的,沒有就繼承最近的,具備「賦予等級」的祖先的「賦予等級」。
        TRACE, DEBUG, INFO, WARN, ERROR, ALL, OFF, INHERITED, NULL(填最後兩個
        等價於省略level,而且最後兩個效果等價)
        三、additivity是可選的,默認是true
        四、一個logger能夠包含零到多個appender-ref元素
        -->
    <logger name="org.sample.logback.Foo" level="OFF" additivity="true" />
    <logger name="org.sample.logback.LogbackTest" level="INFO" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </logger>

    <!-- 配置root元素:
        一、它不支持除了level外的任何其它屬性
        二、appender-ref元素和普通logger同樣
        -->
    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Example2- 變量定義初步

<configuration debug="true">

    <!-- 方法一,簡單變量替換 -->
    <property name="USER_HOME" value="log_files" />
    <!-- 方法二,採用系統屬性(System property)達到一樣效果-->
    <!-- java -DUSER_HOME="log_files" MyApp2 -->
    <!--方法三槓一,經過文件導入變量,當變量多的時候這樣比較方便-->
    <property file="src/main/java/variables1.properties" />
    <!--文件內容USER_HOME=log_files-->
    <!-- 方法三槓二,等效三杆一,不過這個時候資源在類路徑裏 -->
    <property resource="resource1.properties" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${USER_HOME}/myApp.log</file>
        <encoder>
            <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.sample.logback.LogbackTest" level="INFO" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </logger>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

logback徹底支持變量嵌套。變量的名稱、默認值和值定義均可以引用其餘變量:

USER_HOME=/home/sebastien
fileName=myApp.log
destination=${USER_HOME}/${fileName}

再好比${${userid}.password}、${id:-${userid}}。。

Example3- 變量做用域

<configuration>
    <!--
    LOCAL SCOPE
    默認的做用域。變量生命週期:在配置文件中定
    義的位置開始直到配置文件被解析/執行完成。意味
    着每次解析配置文件都將建立一個新的這個變量。

    CONTEXT SCOPE
    插入到上下文(context),直到context被清除。
    一旦定義,CONTEXT SCOPE中的屬性就是context的
    一部分。所以,它在全部日誌事件中均可用,包括
    經過序列化發送到遠程主機的日誌事件。

    SYSTEM SCOPE
    帶有SYSTEM做用域的屬性被插入到JVM的系統屬性中,
    而且持續到JVM清除爲止。
    -->

    <!-- 在替換配置文件中的變量時,變量的查找
        順序是LOCAL>CONTEXT>SYSTEM,最後是操做
         系統環境變量 -->

    <property scope="context" name="nodeId" value="firstNode" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <!-- 用":-"定義默認值 -->
        <file>log_files/${nodeId:-secondNode}/myApp.log</file>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="FILE" />
    </root>
</configuration>

Example4- HOSTNAME和CONTEXT_NAME是默認的兩個變量(好像是惰性初始化的)

<configuration>
    <property scope="context" name="nodeId" value="firstNode" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>log_files/${HOSTNAME}/${CONTEXT_NAME}/myApp.log</file>
        <!--C:\Users\mdzz\Desktop\test-mvn\testlogback\log_files\LAPTOP-QGECNCGO\default\myApp.log-->
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="FILE" />
    </root>
</configuration>

 

Generate

相關文章
相關標籤/搜索