Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Filter Logcat by tag using a regex

When logging my Tags always look like this:

com.myapp.SomeActivity

For each log statement I prepend the first part "com.myapp." to the Tag of the class which is making the log call. For instance:

MyActivity extends Activity{

private static final String TAG = "MyActivity";

 public void someMethod(){
  LogWrapper.e(TAG, "Something is wrong here.");
 } 
}

My class LogWrapper basically does the following

public class LogWrapper {
 private static final String applicationTAG = "com.myapp.";

 public static void e(String classTag, String message){
  Log.e(applicationTAG + classTag, message);
 }
}

So all I do is prepend a static Tag to the class's tag. The reason is, that I want to filter the logcat output by the Log statements my application writes and to avoid cluttering my logfile with logs from the system or other applications.

Hence I came up with obtaining the Logs like this:

String command = "logcat -d -v time com.myapp.*:I *:S"
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);
 log.append(StringUtils.NEW_LINE);
}

However, I end up with an empty logfile. Which makes me thing the regex expression "com.myapp.:I" does not work. I also tried omitting the asterix () but that works neither. However if I use "*:I" that works.

Which makes me wonder, whether it is only possible to filter by a complete tag name? Is there a way I can get hold of a log that's filtered by "com.myapp." ?

I guess plan B would be that in the while loop I could check if the line contains my tag and append it only if that's the case, but I'd really like to avoid that...

like image 701
AgentKnopf Avatar asked Mar 20 '12 13:03

AgentKnopf


1 Answers

Ok to solve the issue I gave up the more elegant (and still unknown) solution for the Plan B I hinted at in my first post. I use the following regex to filter each line of the logfile that I obtained using the command logcat -d -v time *:I (executed using Runtime.getRuntime().exec(command)):

.*([DIWE]{1}/com.myapp.).*

The above regex matches log statements like this:

I/com.myapp.MyClass Crashed and did not recover - too bad.

The [DEWI] means that, the log level must be either D(ebug), E(rror), W(arning) or I(nfo) in order for the regex to match. If you want to extract V(erbose) logging as well, just add a "V" .

like image 161
AgentKnopf Avatar answered Oct 19 '22 03:10

AgentKnopf