SLF4J 教程(自由在各種log中切換)
一、介紹:
簡(jiǎn)單日記門(mén)面(simple logging Facade for java)SLF4J是為各種loging APIs提供一個(gè)簡(jiǎn)單統(tǒng)一的
接口,從而使得最終用戶(hù)能夠在部署的時(shí)候配置自己希望的loging APIs實(shí)現(xiàn)。 Logging API實(shí)現(xiàn)既可以
選擇直接實(shí)現(xiàn)SLF4J接的loging APIs如: NLOG4J、SimpleLogger。也可以通過(guò)SLF4J提供的API實(shí)現(xiàn)
來(lái)開(kāi)發(fā)相應(yīng)的適配器如Log4jLoggerAdapter、JDK14LoggerAdapter。在SLF4J發(fā)行版本中包含了幾個(gè)
jar包,如slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-log4j13.jar,
slf4j-jdk14.jar and slf4j-jcl.jar通過(guò)這些jar文件可以使編譯期與具體的實(shí)現(xiàn)脫離?;蛘哒f(shuō)可以
靈活的切換
二、官方站點(diǎn)
官方的網(wǎng)站:http://www.slf4j.org/manual.html
三、為何使用slf4j?
我們?cè)陂_(kāi)發(fā)過(guò)程中可能使用各種log,每個(gè)Log有不同的風(fēng)格、布局,如果想靈活的切換那么slf4j是比較好的
選擇。
四、如何使用slf4j
下邊一段程序是經(jīng)典的使用slf4j的方法.




























下邊介紹一下運(yùn)行上邊程序的過(guò)程。
1,編譯上邊的程序,需要classpath中加入slf4j-api-1.4.1.jar文件
2,運(yùn)行時(shí),需要classpath中加上slf4j-simple-1.4.1.jar
運(yùn)行得到結(jié)果:
----------------------------
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.
這個(gè)是simple log風(fēng)格,
3,切換:如果想切換到j(luò)dk14的log的風(fēng)格,只需要把slf4j-simple-1.4.1.jar
從classpath中移除,同時(shí)classpath中加入slj4j-jdk14-1.4.1.jar
這時(shí)的運(yùn)行結(jié)果:
---------------------------------------------------
2007-7-9 10:40:15 Wombat setTemperature
嚴(yán)重: Temperature set to 1. Old temperature was null.
2007-7-9 10:40:16 Wombat setTemperature
嚴(yán)重: Temperature set to 55. Old temperature was 1.
2007-7-9 10:40:16 Wombat setTemperature
信息: Temperature has risen above 50 degrees.
已經(jīng)變成jdk14的log風(fēng)格了。
4,再次切換到log4j
同樣移除slj4j-jdk14-1.4.1.jar,加入slf4j-log4j12-1.4.1.jar,同時(shí)加入log4j-1.2.x.jar
加入log4j.properties。得到顯示結(jié)果:
---------------------------------------
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.
在不同的風(fēng)格中切換只需要在部署期切換類(lèi)庫(kù)就可以了,和開(kāi)發(fā)時(shí)無(wú)關(guān)。
posted on 2007-07-09 10:47 dreamstone 閱讀(18242) 評(píng)論(9) 編輯 收藏 所屬分類(lèi): 利器 、其它開(kāi)源框架