Jee Seok Yoon
Jee Seok Yoon

Reputation: 4806

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?

Upvotes: 0

Views: 1960

Answers (2)

An SO User
An SO User

Reputation: 24998

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

Upvotes: 0

Rahul
Rahul

Reputation: 45070

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

Upvotes: 6

Related Questions