Saturday, February 16, 2008

Redirect Std Error to a file

Sometimes may be convenient to save all outcomes from standar error to a file.
This is very easy to do and you need the following lines of code
String filename = "mylog.log";
PrintStream stream = new PrintStream(filename);
System.setErr(stream);

The problem with this approach is that there is no timestamp, like for normal log.
A simply workaround may be to redirect the standard error at every launch to a different file named with the timestamp and to save all the log files in the same folder.
String logFolderName = "log";
File logFolder = new File(logFolderName);
// Create the log folder if it non already exists
if (!logFolder.exists()) {
logFolder.mkdirs();
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm");
StringBuilder sb = new StringBuilder();
sb.append(logFolderName);
sb.append(System.getProperty("file.separator"));
sb.append("mystderr");
sb.append("_");
sb.append(df.format(new Date()));
sb.append(".log");
PrintStream stream = new PrintStream(sb.toString());
System.setErr(stream);

and your exception will be saved in file like this: log/mystderr_2008-02-16_22:09.log

No comments: