Logcat Recorder

Introduction

Logcat is an Android mechanism used to collect and view system debug output. This is extremely useful for debugging and QA testing, as it provides valuable information about what the apps are doing.

Under normal conditions, logcat is visible via Android Device Monitor or directly executed from the ADB shell via the logcat command. The purpose of this tutorial is to present a simple mechanism to programmatically capture and filter logcat entries.

Logcat recorder

First thing’s first, we need a nice way to handle the logcat recorder’s status (recording, new log entry, idle). As a result, we create a simple OnLogcatRecorderListener.java interface to define these events:

Next, we need to define a basic LogcatRecorder.java class and introduce our listener:

Now, we need a mechanism to start() recording the logcat. This will essentially create a new thread (to avoid locking the main UI thread), containing a Runtime Process to execute the logcat shell command and continuously record its output:

We first need to clear the current log via the “logcat -c” runtime process call. Once the log is clear, we can start recording it Runtime.getRuntime().exec(“logcat“) and, optionally, add a filter to our recorder Runtime.getRuntime().exec(“logcat | grep ” + filter)Whilst recording, we call our interface’s onNewLogEntry() method to pass on each new log entry.

To wrap this up, we also need a method to stop() the recording process:

In order to do this, we first check our recorder’s state and simply destroy the logging Runtime Process. Once the recording is done, our interface will serve the full list of recorded log entries via onLogcatRecorderListener.onStopRecording(log.toString());

Finally

We just need to add the LogcatRecorder to a new Activity. First, we define ../res/layout/activity_main.xml:

Finally, we define MainActivity.java and add a new instance of our LogcatRecorder to it:

 

Get the full project on GitHub.

Share this on: