SLF4J 教程(自由在各種log中切換)
一、介紹:
簡單日記門面(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文件可以使編譯期與具體的實現脫離。或者說可以
靈活的切換
二、官方站點
官方的網站:http://www.slf4j.org/manual.html
三、為何使用slf4j?
我們在開發過程中可能使用各種log,每個Log有不同的風格、布局,如果想靈活的切換那么slf4j是比較好的
選擇。
四、如何使用slf4j
下邊一段程序是經典的使用slf4j的方法.




























下邊介紹一下運行上邊程序的過程。
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.
2007-7-9 10:40:16 Wombat setTemperature
信息: 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.
在不同的風格中切換只需要在部署期切換類庫就可以了,和開發時無關。
posted on 2007-07-09 10:47 dreamstone 閱讀(18226) 評論(9) 編輯 收藏 所屬分類: 利器 、其它開源框架