How can I convert a stack trace to a string?

前端 未结 30 1538
再見小時候
再見小時候 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:11

    Here is a version that is copy-pastable directly into code:

    import java.io.StringWriter; 
    import java.io.PrintWriter;
    
    //Two lines of code to get the exception into a StringWriter
    StringWriter sw = new StringWriter();
    new Throwable().printStackTrace(new PrintWriter(sw));
    
    //And to actually print it
    logger.info("Current stack trace is:\n" + sw.toString());
    

    Or, in a catch block

    } catch (Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        logger.info("Current stack trace is:\n" + sw.toString());
    }
    

提交回复
热议问题