예외 스택 추적 인쇄
예외 스택 트레이스를 stderr 이외의 스트림에 인쇄하려면 어떻게 해야 합니까?getStackTrace()를 사용하여 목록 전체를 스트림에 인쇄하는 방법이 있습니다.
아름답지는 않지만, 그래도 해결 방법:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
Throwable.printStackTrace()에는 인수로 인쇄 스트림을 사용하는 대체 형식이 있습니다.http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
예.
catch(Exception e) {
e.printStackTrace(System.out);
}
그러면 스택 트레이스가 std 오류 대신 std out으로 출력됩니다.
Throwable.printStackTrace(..)
할 수 있다PrintWriter
또는PrintStream
인수:
} catch (Exception ex) {
ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}
즉, LOGBack 또는 log4j와 같은 로깅 구현에 SLF4J와 같은 로거 인터페이스를 사용하는 것을 검토해 주십시오.
Android 개발 미니멀리스트의 경우:Log.getStackTraceString(exception)
Apache Commons는 스택 트레이스를 슬로우 가능에서 문자열로 변환하는 유틸리티를 제공합니다.
사용방법:
ExceptionUtils.getStackTrace(e)
상세한 것에 대하여는, https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html 를 참조해 주세요.
stackTrace 취득에 도움이 되는 메서드를 작성했습니다.
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
Throwable 클래스는 다음 두 가지 메서드를 제공합니다.printStackTrace
, 를 받아들인다.PrintWriter
그리고 그 중 하나는PrintStream
스택 트레이스를 지정된 스트림에 출력합니다.이것들 중 하나를 사용하는 것을 고려해보세요.
"javadoc" 참조
out = some stream ...
try
{
}
catch ( Exception cause )
{
cause . printStrackTrace ( new PrintStream ( out ) ) ;
}
보다 콤팩트한 스택트레이스에는 다음과 같은 상세정보(패키지 상세)가 필요합니다.
java.net.SocketTimeoutException:Receive timed out
at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151]
at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^]
at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^]
at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/]
at o.s.n.SntpClient$1.call(^:145)[^]
at ^.call(^:134)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^]
at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^]
at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^]
at ^.requestTimeHA(^:122)[^]
at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/]
at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151]
Throwables를 사용해 보세요.spf4j lib로부터의 write To.
언급URL : https://stackoverflow.com/questions/6822968/print-the-stack-trace-of-an-exception
'source' 카테고리의 다른 글
JavaScript에서만 현재 시간을 얻는 방법 (0) | 2023.01.12 |
---|---|
Pylint와 함께 하나의 특정 라인을 무시할 수 있습니까? (0) | 2023.01.12 |
가장 오래된 항목과 일치하는 모든 항목 선택 (0) | 2023.01.12 |
java.lang의 원인StackOverflowError(스택오버플로우오류) (0) | 2023.01.12 |
Ajax POST 요청으로 인해 장고 CSRF 체크가 실패함 (0) | 2023.01.12 |