1. log.error(“異常資訊:”+e.getMessage)
沒有異常資訊,沒有堆疊資訊
@PostMapping("/logtest") public void logtest(){ try { int i=1/0; } catch (Exception e) { log.error("異常資訊:"+e.getMessage()); } }
測試結果:
2024-03-13 14:12:16.555 | ERROR | http-nio-7012-exec-1 | com.ttbank.flep.controller.UserController:70 | [] | [] - 異常資訊:/ by zero
2 log.error(“異常資訊:”+e)
@PostMapping("/logtest") public void logtest(){ try { int i=1/0; } catch (Exception e) { log.error("異常資訊:"+e); } }
測試結果:
2024-03-13 14:17:02.532 | ERROR | http-nio-7012-exec-1 | com.ttbank.flep.controller.UserController:70 | [] | [] - 異常資訊:java.lang.ArithmeticException: / by zero
3 log.error(“異常資訊:”,e);
最佳實踐。可以得到異常的資訊和堆疊資訊
@PostMapping("/logtest") public void logtest(){ try { int i=1/0; } catch (Exception e) { log.error("異常資訊:", e); } }
測試結果:
2024-03-13 14:22:17.725 | ERROR | http-nio-7012-exec-2 | com.ttbank.flep.controller.UserController:70 | [] | [] - 異常資訊: java.lang.ArithmeticException: / by zero at com.ttbank.flep.controller.UserController.logtest(UserController.java:68) [classes/:?] at com.ttbank.flep.controller.UserController$$FastClassBySpringCGLIB$$adad7f81.invoke(<generated>) [classes/:?]
注意:一般再加一行, e.printStackTrace() 會把 stack trace 資訊直接輸出到控制檯。
4 log.error("eee{}","11111",e); 佔位變數
public void error(String msg, Throwable t);
測試程式碼:
@PostMapping("/logtest") public void logtest(){ String name="lucky"; String address="taitian"; try { int i=1/0; } catch (Exception e) { log.error("異常資訊:{}, {}",name, address, e); } }
在logback的實現裡面有個特殊的處理
會判斷下最後一個引數(注意只在最後)是否是Throwable物件,如果是 ,就列印異常堆疊。
參考文獻:
https://blog.csdn.net/jiangyyyeff/article/details/122580977
https://blog.csdn.net/qq_19642249/article/details/88538303
https://blog.csdn.net/renzhe1301/article/details/121268510