How can I convert a stack trace to a string?

前端 未结 30 1199
再見小時候
再見小時候 2020-11-22 14:51

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

30条回答
  •  醉酒成梦
    2020-11-22 15:13

    Old question, but I would just like to add the special case where you don't want to print all the stack, by removing some parts you are not actually interested in, excluding certain classes or packages.

    Instead of a PrintWriter use a SelectivePrintWriter:

    // This filters out this package and up.
    String packageNameToFilter = "org.springframework";
    
    StringWriter sw = new StringWriter();
    PrintWriter pw = new SelectivePrintWriter(sw, packageNameToFilter);
    e.printStackTrace(pw);
    String sStackTrace = sw.toString(); 
    System.out.println(sStackTrace);
    

    Where the SelectivePrintWriter class is given by:

    public class SelectivePrintWriter extends PrintWriter {
        private boolean on = true;
        private static final String AT = "\tat";
        private String internal;
    
        public SelectivePrintWriter(Writer out, String packageOrClassName) {
            super(out);
            internal = "\tat " + packageOrClassName;
        }
    
        public void println(Object obj) {
            if (obj instanceof String) {
                String txt = (String) obj;
                if (!txt.startsWith(AT)) on = true;
                else if (txt.startsWith(internal)) on = false;
                if (on) super.println(txt);
            } else {
                super.println(obj);
            }
        }
    }
    

    Please note this class may be easily adapted to filter out by Regex, contains or other criteria. Also note it depends upon Throwable implementation details (not likely to change, but still).

提交回复
热议问题