Android - 打印完整异常回溯以记录

dan*_*dan 91 android

我有一个try/catch块抛出异常,我想在Android设备日志中看到有关异常的信息.

我从开发计算机上用此命令读取了移动设备的日志:

/home/dan/android-sdk-linux_x86/tools/adb shell logcat
Run Code Online (Sandbox Code Playgroud)

我先试了一下:

try {
    // code buggy code
} catch (Exception e)
{
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

但是这不会在日志中打印任何内容.这很可惜因为它会有很多帮助.

我取得的最好成绩是:

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

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

你知道如何在日志中打印完整的回溯吗?

谢谢.

Ebo*_*ike 162

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

  • 注意使用e.getMessage() - getMessage()可能返回null,具体取决于抛出的异常类型,这本身会导致异常,因为不支持null作为Log方法中的消息参数.见[here](http://developer.android.com/reference/java/lang/Throwable.html#getMessage%28%29) (27认同)
  • 另外,我的风格:Log.e(e.getClass().getName(),e.​​getMessage(),e); (4认同)

小智 47

这个辅助函数也很好用,因为Exception也是一个Throwable.

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


Mar*_*rer 8

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

或者......你知道...... EboMike说的是什么.