【Java】例外のスタックトレースを文字列に変換するには

はじめに

 * 例外をログに出力するために、ex.getMessage() だけでは情報が足りない時が多い。
   そこで、例外のスタックトレースを文字列にしたい。

サンプル

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionHelper {

   public static void main(String[] args) {
      try {
         int a = 1 / 0;
      } catch (Exception ex) {
         System.out.println("Exception is " + ExceptionHelper.getStackTrace(ex));
      }
   }

   public static String getStackTrace(Exception exception) {
      String returnValue = "";
      try (StringWriter error = new StringWriter()) {
         exception.printStackTrace(new PrintWriter(error));
         returnValue = error.toString();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
      return returnValue;
   }
}

出力結果

Exception is java.lang.ArithmeticException: / by zero
	at com.ant.sample.ExceptionHelper.main(ExceptionHelper.java:11)