2015-01-15 121 views
6

我已阅读this article。但它似乎大部分文本显示不在我的应用程序。我如何过滤邮件并让它只显示我的应用程序的日志。换句话说,我想在Android Studio中显示它(仅显示来自我的应用程序的错误日志,显示时间戳等):以编程方式读取logcat以获得应用程序

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

enter image description here

+1

你总是可以从logcat的自己解析线,而忽略你不希望任何标记。 –

回答

15

尝试下面的代码只得到您的应用程序的日志。

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" /> 
+1

阅读日志的延迟是多少? – Sid

+3

我编辑你的文章,通过添加-d命令行参数logcat,否则函数永远不会返回,只是等待并添加更多的日志行,因为他们发布。同样在Android的新版本(我认为从Jellybean上来)和没有root权限的情况下,只有你自己的应用程序包生成的logcat条目包含在内。 – gregko

+0

@gregko感谢您的编辑:) –

相关问题