JAVA
[ JAVA ] printStackTrace 를 String 형으로 표현 (log4j 등에 사용 가능)
정윤재
2012. 2. 20. 10:48
Exception 클래스의 변수를 argument 로 넣어 주면 String 형으로
에러 메시지가 출력 되는 함수를 만들어 테스트 해보았다
sample code 보면 바로 아실 수 있을 겁니다.
package test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class PrintStackTraceTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String[] a = null;
for(int i=0;i<a.length;i++){
}
}catch(Exception e){
//e.printStackTrace();
e.getMessage();
String str = getPrintStacTraceString(e);
System.out.println(str);
}
}
/**
* String 형으로 printStackTrace message 를 돌려 주는 method
* @param e
* @return
*/
public static String getPrintStacTraceString(Exception e){
String returnValue = "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(out);
e.printStackTrace(printStream);
returnValue = out.toString();
return returnValue;
}
}