Logging things on the device on Android

Jānis Peisenieks
Musings of a Latvian developer
2 min readSep 5, 2013

Edit 2016: This seemed like a good idea back when i started Android development. It's not. Take a look http://www.sureshjoshi.com/mobile/file-logging-in-android-with-timber/ for a better solution.

Once in a blue moon a problem arises which requires us to do some logging on the device while it is not connected. Or better yet, we have created a beta release, to hand over to our testing dept. (read — the project managers :D ), and we would like to know what goes on in our app.

Well I’ve found a couple of solutions out there, that use some sort of elaborate event/log sending to a server or a Google Drive spread sheet or what not. Well, I propose a simple log directory on the users device. We would achieve it by doing something like this:

A custom application file.

First off we need to create a custom application and define in our AndroidManifest.xml file:

Custom onCreate() event in our application

And in our MyApplication file we create a custom onCreate() function with this content:

try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Logs/");
boolean created = false;
if (!dir.exists()) {
created = dir.mkdirs();
}
File filename = new File(Environment.getExternalStorageDirectory()
+ "/Logs/logfile" + dateFormat.format(date) + ".log");
filename.createNewFile();
String cmd = "logcat -f "
+ filename.getAbsolutePath()
+ " -v time ListView:V Prefs:V Splash:V System.err:V MyApplication:V AndroidRuntime:V *:S";
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}

I think this code is quite self-explaining, so I’ll just comment on the cmd line, which is the most important.

What this is saying, that we want to log the logcat output to our file, and we want it to log all of the log events, that have tagName:logPriority . That is it!

Hope this helps someone make their deployment/testing easier :)

--

--