Java保存错误日志信息

我们平时在撸代码的时候,有时候需要将某个代码块的具体错误信息保存到数据库或文件中,以便日后方便快速的查找问题。

使用e.printStackTrace(),我们可以将信息保存在具体的变量中,然后写入数据库或文件。

 1 /**
 2      * 获取错误信息
 3      * 
 4      * @param e
 5      * @return
 6      */
 7     public static String getErrorLog(Exception e) {
 8         StringWriter sw = null;
 9         PrintWriter pw = null;
10         try {
11             sw = new StringWriter();
12             pw = new PrintWriter(sw);
13             // 将出错的栈信息输出到printWriter中
14             e.printStackTrace(pw);
15             pw.flush();
16             sw.flush();
17         } finally {
18             if (sw != null) {
19                 try {
20                     sw.close();
21                 } catch (IOException e1) {
22                     e1.printStackTrace();
23                 }
24             }
25             if (pw != null) {
26                 pw.close();
27             }
28         }
29         return sw.toString();
30     }

 

posted on 2017-08-15 11:03  大地上的乌龟  阅读(607)  评论(0编辑  收藏  举报

导航