8

I've read this article already. But it seems most of the text it shows are not in my application. How can I filter the message and let it only shows the log for my application. In another word, I want to show it like the one in Android Studio (only showing the error log from my app, showing time stamp,etc):

I tried something like "logcat -d -v time", but doesn't work. Any idea? Thanks.

enter image description here

Community
  • 1
  • 1
Bagusflyer
  • 12,675
  • 21
  • 96
  • 179

1 Answers1

18

Try following code to get logs of your application only.

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;
    }
}

Edit

Add below permission to your AndroidManifest file

<uses-permission android:name="android.permission.READ_LOGS" />
Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
  • 3
    I edited your post by adding -d command line parameter to logcat, else the function never returns, just waits and adds more log lines as they are posted. Also under newer versions of Android (I think from Jellybean up) and without root access, only the logcat entries generated by your own app package are included. – gregko Jun 06 '16 at 19:54
  • 1
    Don't forget to add '' in your manifest for this to work. – Dominikus K. Apr 10 '17 at 13:23
  • READ_LOGS added in API level 1 String READ_LOGS Allows an application to read the low-level system log files. Not for use by third-party applications, because Log entries can contain the user's private information. https://developer.android.com/reference/android/Manifest.permission.html#READ_LOGS – fatboy Feb 18 '18 at 03:25
  • is it possible to read logs of other application using package name ? – Sagar Sep 03 '20 at 09:53