爲什麼要使用logger.isErrorEnabled()

很多東西當真都是要用到的時候

1.看下apache的官方的document,在Performance下那塊(From: http://logging.apache.org/log4j/1.2/manual.html)

 

 

 

For example, for some logger cat, writing,

logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));

incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involved.

To avoid the parameter construction cost write:

if(logger.isDebugEnabled() { logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i])); }

This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.

In log4j, logging requests are made to instances of the Logger class. Logger is a class and not an interface. This measurably reduces the cost of method invocation at the cost of some flexibility.

Certain users resort to preprocessing or compile-time techniques to compile out all log statements. This leads to perfect performance efficiency with respect to logging. However, since the resulting application binary does not contain any log statements, logging cannot be turned on for that binary. In my opinion this is a disproportionate price to pay in exchange for a small performance gain.

2.簡單來說,就是用isDebugEnabled方法判斷下是能提升性能的。(From: http://blog.sina.com.cn/s/blog_616b57310100f36s.html )

 if (logger.isInfoEnabled()) {         logger.info("User " + userId + " is using app " + appId);     }
爲什麼要加上logger.isInfoEnabled()?原因有兩點。

1).直接使用logger.info("User " + userId + " is using app " + appId)來輸出log,也能夠達到log級別爲INFO或在INFO以下時才輸出:("User " + userId + " is using app " + appId),因爲logger.info方法內部有判斷輸出級別的代碼。但是在進入logger.info函數之前,("User " + userId + " is using app " + appId) 這個表達式已經通過運算拼接成了一個字符串;而如果事先使用 if (logger.isInfoEnabled())進行判斷,那麼當log級別在INFO以上時,就能省去上述的字符串操作,在高併發和複雜log信息拼接的情況下,使用這種標準的方法輸出log能夠省去不小的系統開銷。另外,如果構造log信息的過程需要大量字符串操作,建議使用StringBuilder來完成字符串拼接。

2).ERROR及其以上級別的log信息是一定會被輸出的,所以只有logger.isDebugEnabled和logger.isInfoEnabled方法,而沒有logger.isErrorEnabled方法。

,纔會拿來仔細研究的。記得當時學的log4j,也就簡單瞭解點,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章