如何用Exception.printStackTrace()包含时间;?

时间:2013-11-05 05:41:05

标签: java exception exception-handling

我正在将所有异常日志写入文本文件中。

例如

pw= new PrintWriter(new FileWriter("EXCEPTION.txt", true));

try
{ 
    do something!! 
} catch (Exception e) {
    e.printStackTrace(pw);pw.flush();
}

但是,当存在多个异常时,很难读取EXCEPTION.txt文件。我认为最好在每个例外之前加入时间。

如何做到这一点?

2 个答案:

答案 0 :(得分:5)

您可以在将堆栈跟踪附加到文件之前添加当前日期。此外,您可以格式化日期并进行编写。

catch (Exception e) {
    pw.write(new Date().toString()); // Adding the date
    pw.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // Formatted date
    e.printStackTrace(pw);
    pw.flush();
}

答案 1 :(得分:0)

你可以这样做:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String timeNow = dateFormat.format(date); // pretty date
pw.write(timeNow + " " + e.getMessage()); // date concatenated with exception message