Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read logcat programmatically for an application

Tags:

android

logcat

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

like image 676
Bagusflyer Avatar asked Jan 15 '15 05:01

Bagusflyer


People also ask

How do I read Logcat logs?

View your app logs To display the log messages for an app: Build and run your app on a device. Click View > Tool Windows > Logcat (or click Logcat in the tool window bar).

How can I see the logs of an Android app?

Android allows collecting system logs using Logcat. Log messages can be viewed in a Logcat window in Android Studio, or you can use the command line tool to pull them. Several Android apps are also available in the Google Play store that allow easy access to these tools.


1 Answers

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" />
like image 151
Chintan Rathod Avatar answered Sep 21 '22 06:09

Chintan Rathod