Android-打印完整的异常回溯到日志

我有一个 try/catch 块,它会抛出一个异常,我希望在 Android 设备日志中看到关于该异常的信息。

我用下面的命令从我的开发计算机中读取移动设备的日志:

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

我先试了这个:

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

但是这并没有在日志上打印出任何东西。这很遗憾,因为这会有很大的帮助。

我取得的最好成就是:

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

总比没有好,但不是很满意。

你知道如何打印完整的回溯到日志?

谢谢。

87154 次浏览
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.

e.printStackTrace() prints it to me. I don't think you're running the logcat correctly. Don't run it in a shell, just run

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

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));
}

The standard output and error output are directed to /dev/null by default so it is all lost. If you want to log this output then you need to follow the instructions "Viewing stdout and stderr" shown here

public String getStackTrace(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
try{
...
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e.getCause());
}

In the context of Android, I had to cast the Exception to a String:

try {
url = new URL(REGISTRATION_PATH);
urlConnection = (HttpURLConnection) url.openConnection();
} catch(MalformedURLException e) {
Log.i("MALFORMED URL", String.valueOf(e));
} catch(IOException e) {
Log.i("IOException", String.valueOf(e));
}

KOTLIN SOLUTION:

You can make use of the helper function getStackTraceString() belonging to the android.util.Log class to print the entire error message on console.

Example:

try {
 

// your code here
    

} catch (e: Exception) {


Log.e("TAG", "Exception occurred, stack trace: " + e.getStackTraceString());


}

Kotlin extension. Returns the detailed description of this throwable with its stack trace.

e.stackTraceToString()

if you want to print out stack trace without exception, you can create it by following command

(new Throwable()).printStackTrace();