JAVA日誌組件系列(三)log4j+logback+slf4j的關係與調試__log4j

來源:互聯網
上載者:User
JAVA日誌組件系列(三)log4j+logback+slf4j的關係與調試 部落格分類: 開源架構 背景
    由於現在開源架構日益豐富,好多開源架構使用的日誌組件不盡相同。存在著在一個項目中,不同的版本,不同的架構共存。導致日誌輸出異常混亂。雖然也不至於對系統造成致命傷害,但是明顯可以看出,架構不夠精良,追求極致略有不足。
    其中有一些標準通用介面,標準實現,各種橋接器的存在,下面就讓筆者樹立一下這些架構之間的關係。

從上圖中,我們可以看到4部分。
介面:將所有日誌實現適配到了一起,用統一的介面調用。
實現:目前主流的日誌實現
舊日誌到slf4j的適配器:如果使用了slf4j,但是只想用一種實現,想把log4j的日誌體系也從logback輸出,這個是很有用的。
slf4j到實現的適配器:如果想制定slf4j的具體實現,需要這些包。

slf4J與舊日誌架構的關係
slf4j等於commons-logging,是各種日誌實現的通用入口,會根據classpath中存在下面哪一個Jar來決定具體的日誌實現庫。
logback-classic(預設的logback實現)
slf4j-jcl.jar(apache commons logging)
slf4j-logj12.jar(log4j 1.2.4)
slf4j-jdk14(java.util.logging)
將所有使用舊式日誌API的第三方類庫或舊代碼的日誌調用轉到slfj
jcl-over-slf4j.jar/jcl104-over-slf4j:apache commons logging 1.1.1/1.0.4,直接替換即可。
log4j-over-slf4j.jar:log4j,直接替換即可。
jul-to-slf4j:jdk logging,需要在程式開始時調用SLF4JBridgeHandler.install()來註冊listener參考JulOverSlf4jProcessor,可在applicationContext.xml中定義該bean來實現初始化。注意原有的log4j.properites將失效,logback網站上提供轉換器,支援從log4j.properties 轉換到logback.xml 。

優勢:轉移到logback的理由
    slf4j支援參數化的logger.error("帳號ID:{}不存在", userId);告別了if(logger.isDebugEnable()) 時代。
    另外logback的整體效能比log4j也較佳,hibernate等項目已經採用了slf4j:"某些關鍵操作,比如判定是否記錄一條日誌語句的操作,其效能得到了顯著的提高。這個操作在LOGBack中需要3納秒,而在Log4J中則需要30納秒。 LOGBack建立記錄器(logger)的速度也更快:13毫秒,而在Log4J中需要23毫秒。更重要的是,它擷取已存在的記錄器只需94納秒,而 Log4J需要2234納秒,時間減少到了1/23。"

slf4j和logback的使用
1.如果日誌的參數超過3個,需要寫成
Object[] params = {newVal, below, above}; logger.debug("Value {} was inserted between {} and {}.", params);
commons-logging 和slf4j的代碼比較:commons-logging 範例程式碼:
Java代碼   import org.apache.commons.logging.Log;   import org.apache.commons.logging.LogFactory;      public class TestLog {       Log log = LogFactory.getLog(TestLog.class);          public void print() {           if (log.isDebugEnabled()) {               log.debug(sql);               log.debug("My name is " + name + ", I am " + age + " years old.");           }       }   }  
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class TestLog {    Log log = LogFactory.getLog(TestLog.class);    public void print() {        if (log.isDebugEnabled()) {            log.debug(sql);            log.debug("My name is " + name + ", I am " + age + " years old.");        }    }}

slf4j的範例程式碼:
Java代碼   import org.slf4j.Logger;   import org.slf4j.LoggerFactory;      public class TestLogBySlf4J {       Logger logger = LoggerFactory.getLogger(TestLogBySlf4J.class);          public void print() {           logger.debug(sql);           logger.debug("My name is {}, I am {} years old.", name, age);       }   }  
import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class TestLogBySlf4J {    Logger logger = LoggerFactory.getLogger(TestLogBySlf4J.class);    public void print() {        logger.debug(sql);        logger.debug("My name is {}, I am {} years old.", name, age);    }}

2.因為內部已最佳化,作者認為slf4j的logger不需要定義為static。
3.可設定緩衝後批量寫記錄檔(但伺服器如果重啟,可能會丟失未寫到磁碟的記錄)
4.MDC,用Filter,將目前使用者名等商務資訊放入MDC中,在日誌format定義中即可使用該變數。
5.JMS Appender用於警示, DB Appender用於業務日誌等

生產環境情況以及優雅方案
    我廠的項目由於使用了眾多的開源架構,所以導致項目中的日誌體系非常混亂。經常出現日誌包衝突的情況。例如:commons-logging-1.0.4,commons-logging-1.1.3,log4j,logback,jboss-logging,java.util.logging......不同的版本,不同的實現。之前筆者至少要配置log4j,logback,commons-logging三個設定檔,才能完成日誌的輸出。研究了日誌體系以後,我廠的maven的pom.xml如下
Xml代碼       <!-- log -->   <dependency>        <groupId>org.slf4j </groupId>        <artifactId>slf4j-api </artifactId>        <version>${org.slf4j-version} </version>   </dependency>   <dependency>        <groupId>org.slf4j </groupId>        <artifactId>jcl-over-slf4j </artifactId>        <version>${org.slf4j-version} </version>   </dependency>   <dependency>        <groupId>org.slf4j </groupId>        <artifactId>log4j-over-slf4j </artifactId>        <version>${org.slf4j-version} </version>   </dependency>   <dependency>        <groupId>org.slf4j </groupId>        <artifactId>jul-to-slf4j </artifactId>        <version>${org.slf4j-version} </version>   </dependency>   <dependency>        <groupId>org.jboss.logging </groupId>        <artifactId>jboss-logging </artifactId>        <version>3.1.4.GA </version>   </dependency>   <!--    <dependency>        <groupId>commons-logging </groupId>        <artifactId>commons-logging </artifactId>        <version>1.1.3 </version>   </dependency>   <dependency>        <groupId>log4j </groupId>        <artifactId>log4j </artifactId>        <version>1.2.17 </version>   </dependency>         -- >  
 <!-- log --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${org.slf4j-version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId><version>${org.slf4j-version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>log4j-over-slf4j</artifactId><version>${org.slf4j-version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jul-to-slf4j</artifactId><version>${org.slf4j-version}</version></dependency><dependency><groupId>org.jboss.logging</groupId><artifactId>jboss-logging</artifactId><version>3.1.4.GA</version></dependency><!-- <dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.3</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency> -->

    加了幾個重要的實現適配器,log4j-over-slf4j,log4j-over-slf4j,jul-to-slf4j。然後jboss-logging部分也進行了統一的版本控制。同時刪除及exclude掉所有log4j,commons-logging的各個版本。適配器和具體日誌實現,不能共存,否則適配器不生效。這樣的話,我們只有logback設定檔即可,因為log4j的輸出已經委託給了slf4j(通過log4j-over-slf4j),而slf4j的預設實現是logback。
其中JUL需要額外執行一行初始化代碼
Java代碼   SLF4JBridgeHandler.install();// jul to slf4j  
SLF4JBridgeHandler.install();// jul to slf4j


常見錯誤調試
【錯誤1】只是一個典型錯誤,主要是錯誤的第二行紅色部分
log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
出現此錯誤是由於沒有log4j設定檔導致。在classpath下添加log4j.xml,並做一些配置即可。配置完以後,啟動輸出
2014-02-25 09:30:31:743[INFO ][com.mchange.v2.log.MLog.<clinit>(MLog.java:80)] - MLog clients using log4j logging.
2014-02-25 09:30:31:780[INFO ][com.mchange.v2.c3p0.C3P0Registry.banner(C3P0Registry.java:204)] - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
即表示回複正常
。例如我的設定檔如下
log4j.xml
Xml代碼   <?xml version="1.0" encoding="UTF-8" ?>   <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >   <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/' >        <appender name="console" class="org.apache.log4j.ConsoleAppender" >            <layout class="org.apache.log4j.PatternLayout" >                <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss:SSS}[%-5p][%l] - %m%n"  />            </layout>        </appender>        <logger name="org.springframework" additivity="false" >            <level value="info"  />            <appender-ref ref="console"  />       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.