Convert Stack Trace to String in JAVA

Asked

Viewed 140 times

4

What would be the best way to convert Stack Trace from a Exception in String?

1 answer

5


I came across this need and doing a web search I found that one great solution on Soen, which allows you to obtain such important information as String, without having to import other libraries:

try {
} catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    sw.toString(); //Aqui obtenho a String
}
  • Interestingly, this is very useful for logging in simpler and smaller applications, without having to keep configuring external libs and configuring unnecessary resources.

  • Yeah, as soon as I used, I already generated a static method to do this debug and another to only store the logs in static file...I thought it was nice to bring to Sopt also.

  • +1, that solution looks good too.

  • Great, post here also @Renan!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.