使用Logger.error方法時只能打印出異常類型,沒法打印出詳細的堆棧信息,使得定位問題變得困難和不方便。java
Logger類下有多個不一樣的error方法,根據傳入參數的個數及類型的不一樣,自動選擇不一樣的重載方法。apache
當error(Object obj)只傳入一個參數時會將異常對象做爲Object使用,並最終當作String打印出來,當使用兩個參數error(String message, Throwable t),且第二個參數爲Throwable時,纔會將完整的異常堆棧打印出來。spa
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @Author: LeeChao
* @Date: 2018/7/25
* @Describe:
* @Modified By:
*/
public class TestLogError {
public static final Logger LOGGER = LogManager.getLogger(TestLogError.class);
public static void main(String[] args) {
try{
// 模擬空指針異常
//Integer nullInt = Integer.valueOf(null);
int[] array = {1,2,3,4,5};
int outBoundInt = array[5];
}catch (Exception e){
// 直接打印,則只輸出異常類型
LOGGER.error(e);
// 使用字符串拼接
LOGGER.error("使用 + 號鏈接直接輸出 e : " + e);
LOGGER.error("使用 + 號鏈接直接輸出 e.getMessage() : " + e.getMessage());
LOGGER.error("使用 + 號鏈接直接輸出 e.toString() : " + e.toString());
// 使用逗號分隔,調用兩個參數的error方法
LOGGER.error("使用 , 號 使第二個參數做爲Throwable : ", e);
// 嘗試使用分隔符,第二個參數爲Throwable,會發現分隔符沒有起做用,第二個參數的不一樣據,調用不一樣的重載方法
LOGGER.error("第二個參數爲Throwable,使用分隔符打印 {} : ", e);
// 嘗試使用分隔符,第二個參數爲Object,會發現分隔符起做用了,根據第二個參數的不一樣類型,調用不一樣的重載方法
LOGGER.error("第二個參數爲Object,使用分隔符打印 {} ",123);
}
}
}
信息輸出:指針
根據方法重載特性,當只輸入一個參數時,此對象會被當作Object進行打印輸出,若是是Exception e的話,這裏直接就toString()。日誌
/**
* Logs a message object with the {@link Level#ERROR ERROR} level.
*
* @param message the message object to log.
*/
void error(Object message);
根據方法重載特性,當第二個參數爲Throwable時,會打印出異常信息,而且包含異常堆棧信息。code
/** * Logs a message at the {@link Level#ERROR ERROR} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void error(String message, Throwable t);
根據方法重載特性,當第二個參數爲Object時,會根據佔位符進行替換並打印出錯誤日誌。orm
/**
* Logs a message with parameters at error level.
*
* @param message the message to log; the format depends on the message factory.
* @param p0 parameter to the message.
*/
void error(String message, Object p0);