You must open file in append mode:
try {
//...
} catch (Exception e) {
try(Writer w = new FileWriter("file.log", true)) {
e.printStackTrace(new PrintWriter(new BufferedWriter(w)));
}
}
If you are not using Java 7, you must remember about closing or at least flushing the Writer
. Or you can have a global Writer
, but then you must synchronize it between threads.
What about simply using some existing Java library like logback, log4j or even java.util.logging
? Simply say:
} catch (Exception e) {
log.error("Opps!", e);
}
...and the framework will log the exception wherever you want, with lots of additional data like thread name, timestamp, additional message, etc. Logback can also show you from which library given stack frame comes from and even print the stack trace starting from root cause (most nested exception).