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

Jee*_*oon 0 java exception-handling exception

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

例如

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

try
{ 
    do something!! 
} catch (Exception e) {
    e.printStackTrace(pw);pw.flush();
}
Run Code Online (Sandbox Code Playgroud)

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

如何才能做到这一点?

Sud*_*hul 6

您只需在将堆栈跟踪追加到文件之前添加当前日期即可。另外,您可以格式化日期并编写日期。

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();
}
Run Code Online (Sandbox Code Playgroud)