Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - print full exception backtrace to log

Tags:

android

I have a try/catch block that throws an exception and I would like to see information about the exception in the Android device log.

I read the log of the mobile device with this command from my development computer:

/home/dan/android-sdk-linux_x86/tools/adb shell logcat

I tried this first:

try {
    // code buggy code
} catch (Exception e)
{
    e.printStackTrace();
}

but that doesn't print anything to the log. That's a pity because it would have helped a lot.

The best I have achieved is:

try {
    // code buggy code
} catch (Exception e)
{
    Log.e("MYAPP", "exception: " + e.getMessage());             
    Log.e("MYAPP", "exception: " + e.toString());
}

Better than nothing but not very satisfying.

Do you know how to print the full backtrace to the log?

Thanks.

like image 666
Dan Avatar asked Dec 03 '10 00:12

Dan


3 Answers

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.

like image 125
EboMike Avatar answered Nov 20 '22 16:11

EboMike


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));
    }
like image 53
George Avatar answered Nov 20 '22 16:11

George


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.

like image 8
Mark Storer Avatar answered Nov 20 '22 15:11

Mark Storer