JAVA使用日誌Log打印異常信息
一、前言
最近公司用上了SonarQube代碼檢測,提示應該用LOGGER.log(…)代替e.printStackTrace()。
經瞭解到:
- 通過e.printStackTrace()會調用System.err將錯誤信息通過流進行打印可能會無意中暴露敏感信息。
- 而通過日誌的形式進行打印,既保持了安全性,還便於輕易查看。
二、代碼
package com.august;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestLogException {
private Logger logger = LoggerFactory.getLogger(TestLogException.class);
private void testLogException(){
try {
int a = 1/0;
}catch (Exception e){
/*
* 錯誤的寫法,打印不出來錯誤信息,控制檯顯示:
* com.august.TestLogException - --------TestLogException-------->: null
*/
logger.error("--------TestLogException-------->:", e.getMessage());
/*
* 正確的寫法1,打印簡略的錯誤信息,控制檯顯示:
* com.august.TestLogException - --------TestLogException-------->:/ by zero
*/
logger.error("--------TestLogException-------->:{}", e.getMessage());
/*
* 正確的寫法2,打印詳細的錯誤信息,控制檯顯示:
* com.august.TestLogException - --------TestLogException-------->:
* java.lang.ArithmeticException: / by zero
* at com.august.TestLogException.testLogException(TestLogException.java:11)
* at com.august.TestLogException.main(TestLogException.java:23)
*/
logger.error("--------TestLogException-------->:", e);
}
}
}