Android - print full exception backtrace to log

try {
    // code that might throw an exception
} catch (Exception e) {
    Log.e("MYAPP", "exception", e);
}

More Explicitly with Further Info

(Since this is the oldest question about this.)

The three-argument Android log methods will print the stack trace for an Exception that is provided as the third parameter. For example

Log.d(String tag, String msg, Throwable tr)

where tr is the Exception.

According to this comment those Log methods "use the getStackTraceString() method ... behind the scenes" to do that.


catch (Exception e) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintStream stream = new PrintStream( baos );
  e.printStackTrace(stream);
  stream.flush();
  Log.e("MYAPP", new String( baos.toByteArray() );
}

Or... ya know... what EboMike said.


public String getStackTrace(Exception e){
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  e.printStackTrace(pw);
  return sw.toString();
}

This helper function also works nice since Exception is also a Throwable.

    try{
        //bugtastic code here
    }
    catch (Exception e)
    {
         Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
    }

Tags:

Android