天天看點

SLF4J log4j 學習筆記一

一、介紹:

簡單日記門面(simple logging Facade for java)SLF4J是為各種loging APIs提供一個簡單統一的

接口,進而使得最終使用者能夠在部署的時候配置自己希望的loging APIs實作。 Logging API實作既可以

選擇直接實作SLF4J接的loging APIs如: NLOG4J、SimpleLogger。也可以通過SLF4J提供的API實作

來開發相應的擴充卡如Log4jLoggerAdapter、JDK14LoggerAdapter。在SLF4J發行版本中包含了幾個

jar包,如slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-log4j13.jar, 

slf4j-jdk14.jar and slf4j-jcl.jar通過這些jar檔案可以使編譯期與具體的實作脫離。或者說可以

靈活的切換

二、官方站點

三、為何使用slf4j?

我們在開發過程中可能使用各種log,每個Log有不同的風格、布局,如果想靈活的切換那麼slf4j是比較好的

選擇。

四、如何使用slf4j

下邊一段程式是經典的使用slf4j的方法.

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class Wombat  {

    final Logger logger  =  LoggerFactory.getLogger(Wombat. class );

    Integer t;

    Integer oldT;

     public void setTemperature(Integer temperature)  {

        oldT  =  t;

        t  =  temperature;

        logger.error( " Temperature set to {}. Old temperature was {}. " , t, oldT);

         if (temperature.intValue()  >   50 )  {

            logger.info( " Temperature has risen above 50 degrees. " );

        } 

    } 

     public static void main(String[] args)  {

        Wombat wombat  =   new Wombat();

        wombat.setTemperature( 1 );

        wombat.setTemperature( 55 );

 }

下邊介紹一下運作上邊程式的過程。

1,編譯上邊的程式,需要classpath中加入slf4j-api-1.4.1.jar檔案

2,運作時,需要classpath中加上slf4j-simple-1.4.1.jar

運作得到結果:

----------------------------

0 [main] ERROR Wombat - Temperature set to 1. Old temperature was null.

0 [main] ERROR Wombat - Temperature set to 55. Old temperature was 1.

0 [main] INFO Wombat - Temperature has risen above 50 degrees.

這個是simple log風格,

3,切換:如果想切換到jdk14的log的風格,隻需要把slf4j-simple-1.4.1.jar

從classpath中移除,同時classpath中加入slj4j-jdk14-1.4.1.jar

這時的運作結果:

---------------------------------------------------

2007-7-9 10:40:15 Wombat setTemperature

嚴重: Temperature set to 1. Old temperature was null.

2007-7-9 10:40:16 Wombat setTemperature

嚴重: Temperature set to 55. Old temperature was 1.

資訊: Temperature has risen above 50 degrees.

已經變成jdk14的log風格了。

4,再次切換到log4j

同樣移除slj4j-jdk14-1.4.1.jar,加入slf4j-log4j12-1.4.1.jar,同時加入log4j-1.2.x.jar

加入log4j.properties。得到顯示結果:

---------------------------------------

10:42:27,328 ERROR Wombat: Temperature set to 1. Old temperature was null.

10:42:27,328 ERROR Wombat: Temperature set to 55. Old temperature was 1.

10:42:27,328  INFO Wombat: Temperature has risen above 50 degrees.

在不同的風格中切換隻需要在部署期切換類庫就可以了,和開發時無關。

本文轉自追光的貓部落格51CTO部落格,原文連結http://blog.51cto.com/ql0722/1656027如需轉載請自行聯系原作者

00_yatou