使用SLF4J打印日誌---打印異常日誌注意點

使用SLF4J打印日誌的好處可以參見下面兩篇文章:

1.  爲什麼要使用SLF4J而不是Log4J

2.  [日誌處理]slf4j的優勢與使用原理



使用SLF4J打印日誌,它有一個佔位符(place holder){},一般不是異常的是這樣打印的:

logger.info("InvestmentFacadeImpl queryInvestmentInfo: investmentListResponse is {}", investmentListResponse);

{} 就是一個佔位符,那麼打印出來的結果就是

InvestmentFacadeImpl queryInvestmentInfo: investmentListResponse is ********

如果是異常,那麼該怎麼打印呢?

一個錯誤的示範:

logger.error("CrowdFundingAssetServiceImpl insert throws exception is {}", e.getMessage());

其實我們可以去看一下error() 方法的源碼,就知道正確的打印方式了:

 /**
   * Log an exception (throwable) at the ERROR level with an
   * accompanying message.
   *
   * @param msg the message accompanying the exception
   * @param t   the exception (throwable) to log
   */
  public void error(String msg, Throwable t);

對於異常,是不需要佔位符的,而且也不需要e.getMessage(),直接打印出來即可

logger.error("FinancingManualFacadeImpl.addFinancingProduct failed! ", e);

那對於爲什麼要用SLF4J,而不是Log4J或者其他日誌類庫,它的優勢在哪裏,後面會再研究一下

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