logger.isDebugEnabled()的做用

在項目中常常會看到這樣的代碼:this

if (logger.isDebugEnabled()) {
    logger.debug(message);
}

爲何要這樣作呢?spa

  且看isDebugEnabled()的源碼:debug

public boolean isDebugEnabled() {    
  if(repository.isDisabled( Level.DEBUG_INT))
      return false;
  return Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel());
}

  如下是debug()的源碼:日誌

public void debug(Object message) {
    if(repository.isDisabled(Level.DEBUG_INT))
        return;
    if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) {
        forcedLog(FQCN, Level.DEBUG, message, null);
    }
}

  可見,debug()中作了跟isDebugEnabled()幾乎同樣的判斷,看起來直接調用debug()比先判斷isDebugEnabled()更加效率。 
  此時來看下面的代碼: 
logger.debug("The money is " + getTotalMoney());code

  假設咱們的日誌級別設置爲info,debug()方法調用後會判斷if(repository.isDisabled(Level.DEBUG_INT)),而後return。可是在調用debug()方法時,必須提供參數。要得到參數,就須要執行getTotalMoney()並拼接。假設這個獲取參數的過程須要10秒鐘,則系統會在花費10秒後決定return,這顯然很得不償失。 
  加上logger.isDebugEnabled()判斷,只會使寫日誌的時間增長大概萬分之一,可是若是不加此判斷,系統可能須要花費更多的時間,因此在大多數狀況下,在輸出debug日誌前加上logger.isDebugEnabled()比較好。 get

相關文章
相關標籤/搜索