key words: commons log,log4j,apache log
前言: 對于log4j雖然在用,但是也存在一個疑問,怎么有的用apache的commons logging有的直接用log4j,下面的這篇文章解釋了我的疑問.
轉(zhuǎn)自
hereApache組織開發(fā)了一套用于支持Logging的Log4J,Java?1.4版本也引入了一套內(nèi)置的 Logging框架,如果開發(fā)者想在這兩套Logging系統(tǒng)之間自由的切換,該怎么辦呢?答案就是,使用Commons?Logging。 Commons?Logging定義了一套抽象的Logging接口,用戶可以通過配置,使這些接口指向任何一個已存在的Logging系統(tǒng)。
?使用抽象Logging接口
問題:
你在編寫一個可以重復(fù)使用的庫,需要寫入Log信息,但你不想使你的Logging功能綁定在Apache?Log4J或者JDK?1.4?Logging框架上。
解決方案:
public?static?void?main(String[]?args)?{//自己替換[]
??System.setProperty("org.apache.commons.logging.Log", ??????"org.apache.commons.logging.impl.Jdk14Logger"); ??Log?log?=?LogFactory.getLog("com.discursive.jccook.SomeApp");
??if?(log.isTraceEnabled())?{ ????log.trace("This?is?a?trace?message"); ??}
??if?(log.isDebugEnabled())?{ ????log.debug("This?is?a?debug?message"); ??}
??log.info("This?is?an?informational?message"); ??log.warn("This?is?a?warning"); ??log.error("This?is?an?error"); ??log.fatal("This?is?fatal");
}
|
LogFactory.getLog方法會根據(jù)底層環(huán)境返回一個適當(dāng)?shù)腖og實(shí)現(xiàn)。如果用戶想指定一個具體的Logging系統(tǒng)實(shí)現(xiàn),可以設(shè)置org.apache.commons.logging.Log系統(tǒng)屬性。例如:
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.Log4JLogger");
這樣就會使用Log4J作為Logging系統(tǒng)。
org.apache.commons.logging.Log可以設(shè)定為:
?org.apache.commons.logging.impl.Log4JLogger??使用Log4J
?org.apache.commons.logging.impl.Jdk14Logger??使用JDK?1.4?Logging框架
?org.apache.commons.logging.impl.SimpleLog??使用Commons?Logging內(nèi)置的簡單Log實(shí)現(xiàn)
其他:
總結(jié)一下,Commons?Logging會按照下列順序來指定具體的Log實(shí)現(xiàn)。
?如果定義了org.apache.commons.logging.Log系統(tǒng)參數(shù),實(shí)用指定的Logging實(shí)現(xiàn)。
?如果在CLASSPATH里發(fā)現(xiàn)了Log4J,使用Log4J。
?如果使用的是JDK1.4,使用JDK1.4內(nèi)置的Logging框架。
?如果都沒有找到,則使用Commons?Logging內(nèi)置的簡單Log實(shí)現(xiàn)。