Search code examples
androidandroid-logcatandroid-log

android how to capture only my log entries in the application programmatically


I want to get my log entries alone which i had put in the application and show it in the scrollable textview. For example

Log.e(SAMPLE_ACTIVITY_TAG, "App started") 

I need those error logs alone and i dont want other unwanted logs. Is it possible by logcat command line tools ? I have tried the below code but i am getting complete application device logs

 Process process = Runtime.getRuntime().exec("logcat -d");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            log.append(line +"\n");
        }
        textView.setText(log.toString());
        textView.setMovementMethod(new ScrollingMovementMethod());

Any suggestions


Solution

  • Please create process object with below given command:

    logcat --pid=PID -d

    you need to replace PID with your application process id. process id can be fetched using below line of code

    int pid = android.os.Process.myPid();
    

    Your final source code should be like this. Please give it a try

            int pid = android.os.Process.myPid();
            String command = "logcat --pid="+pid+" -d";
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
    
            StringBuilder log=new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                log.append(line +"\n");
            }
            textView.setText(log.toString());
            textView.setMovementMethod(new ScrollingMovementMethod());