0

I am working on Android app in which I am trying to output the contents of logcat into a file on the sdcard.

I am aware of the fact that

  • From JellyBean 3P apps do not have access to system logs. However, I believe using logcat within my app, outputs atleast the log messages put out by my app.
  • Using WRITE_EXTERNAL_STORAGE permission in my manifest file.

    protected void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
      //Code 1 - Seems like an app hang. Nothing shown.
      Process process = Runtime.getRuntime().exec("logcat -f /sdcard/mylog");
    
      //Code 2 - This works however if I run this alone, without the above. 
      FileWriter writer = new FileWriter("/sdcard/mylog");
      writer.append("test");
      writer.close();
    }
      catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

I am testing my app on a device running kitkat.

What am I doing wrong here?

1

2 Answers 2

0

When you run the command logcat it doesn't stop, it keeps running unless you ask it stop (Ctrl + C). You need to use logcat dump so that it dumps the logcat and stops.

logcat -d

This will dump the current contents of the logcat and finish once done.

Edit:

This wont work from the devise without root permissions anymore, starting from Jellybean.

6
  • yes i tried that too. Using "logcat -d -f /sdcard/mylog" didn't seem to be helpful as well.
    – somesh
    Jul 4, 2014 at 11:16
  • Oh, seems like it wont work from the device side anymore. You need root permission to be able to use logcat command now. Jul 4, 2014 at 11:26
  • Did you set android.permission.READ_LOGS permission in your manifest file?
    – busylee
    Jul 4, 2014 at 12:02
  • Hiemanshu, can you please quote the source where you found that info? busylee, yes I did.
    – somesh
    Jul 4, 2014 at 12:20
  • @Hiemanshu, If it needs root permision to read log file on phone, how adb did it? I think it isn't right.
    – busylee
    Jul 4, 2014 at 12:29
0

You can try this code:

try {
            Process process = Runtime.getRuntime().exec("logcat -f");

            Log.d("TAG", "my test phrase");

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

            StringBuilder log=new StringBuilder();
            String line;

            FileWriter fw = new FileWriter("/sdcard/mylog");

            while ((line = bufferedReader.readLine()) != null) {
                fw.append(line);
            }

            fw.close();
        } catch (IOException e) {
        }

This works for me. Hope it helps.

More info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.