Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an exception's StackTrace into a file in java?

In java, when we catch a exception, we usually can use printStackTrace() method to print the error information, and we can also use printStackTrace(PrintStream out) to direct those information to a file.

But how can I append those information into a existing file, just like using out.append()?

like image 520
Yishu Fang Avatar asked Jul 24 '26 00:07

Yishu Fang


2 Answers

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).

like image 50
Tomasz Nurkiewicz Avatar answered Jul 26 '26 16:07

Tomasz Nurkiewicz


We can redirect the error stream to a file

System.setErr(new PrintStream(new FileOutputStream("errors.txt", true), true));

then Throwable.printStackTrace() will print to errors.txt.

"true" in FileOutputStream constructor means "append"; "true" in PrintStream condtructor means "autoflush". We do not need to worry about never closing FileOutputStream, OS will close it when the app ends.

like image 41
Evgeniy Dorofeev Avatar answered Jul 26 '26 15:07

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!