Tuesday, March 27, 2012

Catch LogCat programmatically or export it to file

UPDATE - THIS POST IS VALID ONLY FOR API < 16 (ANDORID 4.1 JELLY BEAN), OTHERWISE YOU NEED ROOT PERMISSION 




Let'see how to catch LogCat from code.
It's very simple, just remember how to call it, and read his input stream.


LogCat process can be launched with parameters such as -help for help,
-s for silent filter,
-d for dump
-c for clear and,
-f for file export.

The (Nyan)LogCat
Those parameters can be combined together.
If you don't specify -s (or *:S) you'll see the entire log.

-s stands for silent, LogCat will print informations only from "myTag".
String myCommand="logcat -s myTag";
Process process = Runtime.getRuntime().exec(myCommand);

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

StringBuilder log=new StringBuilder();
String line = "";

while ((line = bufferedReader.readLine()) != null) 
{
        log.append(line);
        //handler.sendMessage(...); bring message to mainThread
}
You can print more tags at time and specify for each tag which level of log needs priority.
String myCommand="logcat myTag *:S"; //the equivalent of logcat -s myTag
myCommand="logcat -s myTag:D"; //priority to 'debug level' for myTag
myCommand="logcat -s myTag:E myTag2:D"; //priority to 'error level' for myTag and 'debug level' for myTag2, nothing else is showed
myCommand="logcat myTag:E myTag2:D"; //priority to 'error level' for myTag and 'debug level' for myTag2, everything is showed

Remember if you don't specify -d logcat will keep printing log.

If you only need to export a logcat file, you can use -f parameter and specify output path. For example:
String myCommand="logcat -f /sdcard/output.txt"; //no filters, keep writing
myCommand="logcat -d -f /sdcard/output.txt"; //no filters, just a dump
I recommend this notation that can be combined with a filter:
myCommand="logcat -d myTag:V *:S > /sdcard/output.txt"; 
//write a dump for myTag (lever verbose) ,nothing else

Here the official reference for adb and LogCat.

2 comments:

  1. Replies
    1. no it doesn't unless you grant root permission
      you should provide your own log method or use adb at least

      Delete