programing

printStackTrace를 문자열에 저장하는 방법

copyandpastes 2022. 7. 20. 22:49
반응형

printStackTrace를 문자열에 저장하는 방법

어떻게 하면e.printStackTrace()저장하다String가변적인가요?에 의해 생성된 문자열을 사용하고 싶다.e.printStackTrace()내 프로그램 후반부에.

아직 자바에 익숙하지 않아서StringWriter그게 해답이 될 것 같아요.아니면 다른 아이디어가 있으면 알려주세요.고마워요.

뭔가...

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

그게 네게 필요한 거겠지

관련 문서:

Guava는 Throughables.getStackTraceAsString(Troughable)을 사용하여 이를 쉽게 할 수 있습니다.

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

내부적으로는 @Zach L이 제안하는 것을 실행합니다.

를 사용할 수 있습니다.ExceptionUtils.getStackTrace(Throwable t);Apache Commons 3 클래스에서org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(투척 가능t)

코드 예:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}

사용하셔야 합니다.getStackTrace ()대신 방법printStackTrace()다음은 좋은 입니다.

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 

과바에 따라 Apache Commons Lang은ExceptionUtils.getFullStackTraceorg.apache.commons.lang.exceptionStack Overflow에 대한 이전 답변에서.

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

apache commons-lang3 lib 사용

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

//...

String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}

언급URL : https://stackoverflow.com/questions/4812570/how-to-store-printstacktrace-into-a-string

반응형