1

所以我正在编写一个分析器,它需要能够在分析会话期间记录异常。我的计划是使用 logcat 转储到 SD 卡或内部存储上的文件,然后当分析会话完成时,压缩文件并将其发送到服务器。我在清单中添加了android.permission.READ_LOGS,我的代码如下:

public void startLoggingExceptions() {
    String filename = null;
    String directory = null;
    String fullPath = null;
    String externalStorageState = null;

    // The directory will depend on if we have external storage available to us or not
    try {
        filename = String.valueOf(System.currentTimeMillis()) + ".log";
        externalStorageState = Environment.getExternalStorageState();

        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            if(android.os.Build.VERSION.SDK_INT <= 7) {
                directory = Environment.getExternalStorageDirectory().getAbsolutePath();
            } else {
                directory = ProfilerService.this.getExternalFilesDir(null).getAbsolutePath();
            }
        } else {
            directory = ProfilerService.this.getFilesDir().getAbsolutePath();
        }

        fullPath = directory + File.separator + filename;

        Log.w("ProfilerService", fullPath);
        Log.w("ProfilerService", "logcat -f " + fullPath + " *:E");

        exceptionLogger = Runtime.getRuntime().exec("logcat -f " + fullPath + " *:E");
    } catch (Exception e) {
        Log.e("ProfilerService", e.getMessage());
    }
}

exceptionLogger 是一个Process对象,然后我会exceptionLogger.destroy()在分析会话完成时调用它。

我看到的行为是文件是在我指定的位置创建的,但文件中从来没有任何日志输出。我在模拟器中使用开发工具应用程序来强制在日志中显示未处理的异常,但我的 logcat 输出文件仍然为空。有什么想法吗?

编辑:所以当我进入 adb shell,然后 SU 到分配给我的应用程序的用户帐户时,我在运行 logcat 时看到以下内容:

Unable to open log device '/dev/log/main': Permission denied

我曾认为将清单权限添加到我的应用程序将允许我这样做?

4

2 回答 2

14

这个故事的寓意是:仔细检查您在清单文件中的权限是否实际上是 READ_LOGS 而不仅仅是 READ_LOG。

于 2011-06-02T19:48:04.873 回答
2

以防万一有人遇到我遇到的同样问题:尝试从单元测试中读取 logcat 时,需要将权限添加到被测应用程序,而不是测试项目。仅将权限添加到测试项目仍会出现权限错误。

于 2012-12-18T06:53:42.877 回答