【问题标题】:Read logcat programmatically for an application以编程方式读取应用程序的 logcat
【发布时间】:2015-01-15 05:25:49
【问题描述】:

我已经读过this article。但它显示的大部分文本似乎不在我的应用程序中。如何过滤消息并让它只显示我的应用程序的日志。换句话说,我想像在 Android Studio 中那样显示它(仅显示我的应用程序中的错误日志,显示时间戳等):

我尝试了类似“logcat -d -v time”之类的方法,但不起作用。任何的想法?谢谢。

【问题讨论】:

  • 您始终可以自己解析来自 logcat 的行,而忽略任何您不想要的标签。

标签: android logcat


【解决方案1】:

尝试使用以下代码仅获取您的应用程序的日志。

public final class MyAppLogReader {

    private static final String TAG = MyAppLogReader.class.getCanonicalName();
    private static final String processId = Integer.toString(android.os.Process
            .myPid());

    public static StringBuilder getLog() {

        StringBuilder builder = new StringBuilder();

        try {
            String[] command = new String[] { "logcat", "-d", "-v", "threadtime" };

            Process process = Runtime.getRuntime().exec(command);

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(processId)) {
                    builder.append(line);
                    //Code here
                }
            }
        } catch (IOException ex) {
            Log.e(TAG, "getLog failed", ex);
        }

        return builder;
    }
}

编辑

在您的AndroidManifest 文件中添加以下权限

<uses-permission android:name="android.permission.READ_LOGS" />

【讨论】:

  • 我通过将 -d 命令行参数添加到 logcat 来编辑您的帖子,否则该函数永远不会返回,只是等待并在发布时添加更多日志行。同样在较新版本的 Android 下(我认为是从 Jellybean 开始)并且没有 root 访问权限,仅包含您自己的应用程序包生成的 logcat 条目。
  • 不要忘记在你的清单中添加 '' 以使其正常工作。
  • 在 API 级别 1 中添加的 READ_LOGS 字符串 READ_LOGS 允许应用程序读取低级别系统日志文件。不供第三方应用程序使用,因为日志条目可以包含用户的私人信息。 developer.android.com/reference/android/…
  • 是否可以使用包名读取其他应用程序的日志?
猜你喜欢
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
相关资源
最近更新 更多