以前就对日志的打印比较模糊,也没有仔细研究过,直接log.info或者log.error就输出e了,现在模拟异常,对异常进行写表操作,所以需要完整的堆栈信息的.
public static void main(String[] args) throws IOException {
try {
int i = 5 / 0;
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
System.out.println("e.obj:" + e);
System.out.println("e.toString:" + e.toString());
System.out.println("e.message:" + e.getMessage());
System.out.println("e.json:" + GsonUtil.toJson(e));
System.out.println("e.print" + getStackTrace(e));
}
}
public static String getStackTrace(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
对于第一个 e.printStackTrace();,可以看到堆栈信息被打印了出来。但是返回值为void 不能直接用
对于第二个输出obj,第三个tostring,打印出了错误原因,没有类名和详细信息。
对于第四个getMeaage,只是打印出了异常的具体信息,既没有异常类名,也没有堆栈信息。
对于第五个json输出语句,打印出了异常的具体信息
对于最后一个输出语句,完整的各种信息,将一种输出转化为日志
结论:
应该使用最后两种语句的形式来将堆栈信息打印出来,方便日后定位bug,排除错误