If you have a log system, such as slf4j or log4j, sometimes you want to print the exception’s stack trace into log system (a file, a console or something else). Default behavior of e.printStackTrace() is to print the stack trace into stdout.
The easiest way is to convert the stack trace into string then call logger.debug() to print it into log system.
How to do it? Here is a simple solution to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class StackTracePrinter { /** * Print exception stack into string. * @param e the exception. * @return the exception stack. */ public static String printToStr(Exception e) { OutputStream output = new OutputStream() { private StringBuilder sb = new StringBuilder(); @Override public void write(int b) throws IOException { sb.append((char)b); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return sb.toString(); } }; PrintStream prtStream = new PrintStream(output); e.printStackTrace(prtStream); // PrintStream will not flush automatically. prtStream.flush(); return output.toString(); } } |
This sample also show you the flexability of OutputStream.