티스토리 뷰

JAVA에서 Exception 발생 시 printStackTrace 하는 것이 아닌 문자열로 추출하기

Apache에서 제공하는 ExceptionUtils 클래스를 이용하여 문자열 추출을 하고자 하는데 어느 버전부터 지원하는지 모르겠지만 2.6 버전에서도 지원하는 것을 보면 그 이후(2010년) 부터는 다 지원할 듯 합니다.

주요함수를 다음과 같습니다.

String getMessage(Throwable e) : 마지막 에러의 짧은 문자열을 가져옵니다.
String getRootCauseMessage(Throwable e) : 마지막 에러 이전의 에러에 대한 짧은 문자열을 가져옵니다.
String getStackTrace(Throwable e) : Throwsble 로부터 StackTrace를 String 문자열로 가져옵니다.

 


import org.apache.commons.lang3.exception.ExceptionUtils;

	@Test
	public final void runTraceTest() {
	
	  try {
	
	    throw new RuntimeException("RuntimeException 오류 발생 ", 
	          new Exception("Exception 오류발생", 
	          new Throwable("Throwable 발생 ")));
	
	  } catch(Exception e) {
	
	    System.out.println(" e.getMessage() : " + e.getMessage());
	    System.out.println(" ExceptionUtils.getMessage(e) : " + ExceptionUtils.getMessage(e));
	    System.out.println(" ExceptionUtils.getRootCauseMessage(e) : " + ExceptionUtils.getRootCauseMessage(e));
	    System.out.println(" ExceptionUtils.getThrowableCount(e) : " + ExceptionUtils.getThrowableCount(e));    
	    System.out.println(" ExceptionUtils.getThrowables(e) : " );
	    
	    for(final Throwable  el : ExceptinUtils.getThrowable(e)) {
	      System.out.println(el.getMessage());
	    }
	
	     System.out.println(" ExceptionUtils.indexOfThrowable(e, RuntimeException.class) : " + 
	                          ExceptionUtils.indexOfThrowable(e, RuntimeException.class));
	     System.out.println(" ExceptionUtils.indexOfThrowable(e, Throwable.class) : " +                                
	                          ExceptionUtils.indexOfThrowable(e, Throwable.class));
	     System.out.println(" ExceptionUtils.getFullStackTrace(e) : " + ExceptionUtils.getFullStackTrace(e));  
	    
	    StringBuffer err = new StringBuffer();
	    for(final String el : ExceptionUtils.getRootCauseStackTrace(e)) {
	      err.append(el).append("\n");
	    }
	    System.out.println(" ExceptionUtils.getRootCauseStackTrace(e) : " + err.toString() );
	  
	  }
	}

 

오류가 발생하였을 때 로그 상에 클래스 정보가 남는 것을 허용하지 않는 곳이 많죠. 보안 정책 상 이런 조치들이 필요하기는 하지만 정작 문제가 생겼을 때 오류 원인을 찾기 위해서 어느 정도 정보를 남기고 로그 파일에 대한 보안을 강화하는 것도 방법일 듯 합니다.

 

참고 사항 :

getCause(Throwable e) 은 더 이상 지원하지 않으니 버전 4부터는 Throwable.getCause() 를 대신 사용해야 합니다.

getCause(Throwable e, String[] methodNames) 도 버전 4부터 지원하지 않습니다. 

getDefaultCauseMethodNames() 는 버전 4에서 부터 제거되었습니다.

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday