简体   繁体   中英

How to include time with Exception.printStackTrace();?

I am writing all my exception log in a text file.

For example

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

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

However, it is very hard to get the read the EXCEPTION.txt file when there are multiple exceptions. I think it would be better to include time in front of each exception.

How can this be done?

You could simply add the current date just before appending your stacktrace to the file. Also, you can format the date and write it.

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();
}

You could do that as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM