Android Studio中未显示日志记录和崩溃堆栈跟踪

8

我正在尝试在我的设备上调试一个应用程序,但是我在调试器方面遇到了一些麻烦。我尝试测试日志记录器是否会像下面这样写入Logcat:

Log.d("MyActivity", "Testing logging...");

但是使用 app: com.myapp.debug 过滤器在 Logcat 中没有任何显示。当我仅使用我的应用程序名称进行字符串过滤时,它会出现,但条目看起来像这样:

01-08 13:45:07.468  29748-29748/? D/MyActivity﹕ Testing logging...

这个问号是否意味着应用程序中的某些内容没有传递到调试器?这可能与我的第二个调试器问题有关:

我一直在调试一个崩溃,每次发生时,手机只是显示“应用程序未响应”消息,然后关闭当前活动,断开调试器,应用程序继续运行以前的活动。没有堆栈跟踪,没有有关崩溃的信息。我需要在Android Studio中设置什么才能使其正常工作吗?


4
我经常发现基于包名的过滤会防止日志输出在logcat中显示,原因不明。如果要诊断ANR问题,我建议:在logcat中删除所有过滤,并将日志级别切换为“警告”(而非“错误”)。然后滚动输出以查看是否出现关于ANR的任何详细信息。 - stkent
我不确定,但我遇到过类似的问题。只需点击“运行”->“恢复”。 - Martin Pfeffer
当我在 AS 1.0 中按照我的应用程序包名称筛选时,我遇到了类似的问题,Logcat 中什么也看不到。删除过滤器后,可以查看来自设备的所有内容。 - Mike Fosker
谢谢大家,是的,字符串过滤似乎正常工作了。虽然我在崩溃时仍没有直接进入堆栈跟踪,但至少我可以在Logcat中看到跟踪信息,这是一些进展!除非有人弄清楚情况,否则最好保留此问题的开放状态。 - benwad
4个回答

13
我也遇到了这个问题,但是我找不到一个好的解决方案。 相反,我使用了一种方法来捕获错误,即使用Thread.setDefaultUncaughtExceptionHandler()并使用Log.e()记录它。
我使用了这个类来实现。
  public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
   private final String LINE_SEPARATOR = "\n";
   public static final String LOG_TAG = ExceptionHandler.class.getSimpleName();

  @SuppressWarnings("deprecation")
  public void uncaughtException(Thread thread, Throwable exception) {
    StringWriter stackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(stackTrace));

    StringBuilder errorReport = new StringBuilder();
    errorReport.append(stackTrace.toString());

    Log.e(LOG_TAG, errorReport.toString());

    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(10);
   }
}

然后在我的Activity中。

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /**
     * catch unexpected error
     */
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

    setContentView(R.layout.activity_main);

    //other codes
   }

希望这对你有所帮助。

感谢这个有用的课程。 - ondermerol
这非常有用,我已经苦恼了几周。 - Botond Kopacz
如果您创建一个PrintWriter()变量,然后调用flush()函数,那么这个答案就可以完整了。 - melikaafrakhteh

4
我认为这是adb或filer的问题。首先删除所有过滤器。重新启动adb-在终端中键入adb kill-server && adb start-server。

感谢指出筛选器问题,看起来我的筛选器意外地设置为 Firebase,因此 LogCat 上几乎没有日志显示。 - Neon Warge
@NeonWarge 你救了我的一天!!为什么过滤器设置成firebase呢? - Ishaan

2

0
你应该定义一个实现了UncaughtExceptionHandler接口的类,并在Kotlin中使用stackTraceToString
import android.util.Log
import java.lang.Thread.UncaughtExceptionHandler

class ExceptionHandler : UncaughtExceptionHandler {
    override fun uncaughtException(t: Thread, e: Throwable) {
        val stackTrace: String = e.stackTraceToString()

        Log.d("TAG", stackTrace)
    }
}

并在您的应用程序中注册它:

Thread.setDefaultUncaughtExceptionHandler(ExceptionHandler())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接