天天看點

Java日志架構(三):JCL簡介使用原理

JCL

  • 簡介
    • 官方網址
    • 手冊位址
  • 使用
    • maven依賴
    • java使用
  • 原理
    • Log類的實作
    • 實作流程
    • LogFactory

簡介

JCL(Jakarta Commons Logging)

是Apache提供的一個通用日志API。

它提供給中間件/日志工具開發者一個簡單的日志操作抽象,允許程式開發人員使用不同的具體日志實作工具: Log4j, Jdk自帶的日志(JUL), SimpleLog(JCL自己實作的日志實作類)

官方網址

http://commons.apache.org/proper/commons-logging/index.html

手冊位址

http://commons.apache.org/proper/commons-logging/guide.html

使用

maven依賴

<dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
           

java使用

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

Log log = LogFactory.getLog(JclDemo.class);
log.info("test start ");

           

原理

JCL 有兩個基本的抽象類:Log(基本記錄器)和LogFactory(負責建立Log執行個體)。

Log類的實作

Java日志架構(三):JCL簡介使用原理

實作流程

當commons-logging.jar被加入到 CLASSPATH之後,它會心可能合理地猜測你喜歡的日志工具,然後進行自我設定,使用者根本不需要做任何設定。預設的LogFactory是按照下列的 步驟去發現并決定那個日志工具将被使用的(按照順序,尋找過程會在找到第一個工具時中止):

  1. 尋找目前factory中名叫org.apache.commons.logging.Log配置屬性的值
  2. 尋找系統中屬性中名叫org.apache.commons.logging.Log的值
  3. 如果應用程式的classpath中有log4j,則使用相關的包裝(wrapper)類(Log4JLogger)
  4. 如果應用程式運作在jdk1.4的系統中,使用相關的包裝類(Jdk14Logger)
  5. 使用簡易日志包裝類(SimpleLog)

LogFactory

LogFactory

的實作類

org.apache.commons.logging.impl.LogFactoryImpl

, 用于選擇哪個日志實作方式

/**
     * The names of classes that will be tried (in order) as logging
     * adapters. Each class is expected to implement the Log interface,
     * and to throw NoClassDefFound or ExceptionInInitializerError when
     * loaded if the underlying logging library is not available. Any
     * other error indicates that the underlying logging library is available
     * but broken/unusable for some reason.
     */
    private static final String[] classesToDiscover = {
            "org.apache.commons.logging.impl.Log4JLogger",
            "org.apache.commons.logging.impl.Jdk14Logger",
            "org.apache.commons.logging.impl.Jdk13LumberjackLogger",
            "org.apache.commons.logging.impl.SimpleLog"
    };

        for(int i=0; i<classesToDiscover.length && result == null; ++i) {
            result = createLogFromClass(classesToDiscover[i], logCategory, true);
        }

           

在上面4個實作類中選擇一個, 優先

log4j

, 然後是

jul(org.apache.commons.logging.impl.Jdk14Logger)

如果pom引入了

log4j

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
           

會優先使用

log4j

,

如果沒引入實作類, 則使用

jul(org.apache.commons.logging.impl.Jdk14Logger)