Sunday, July 19, 2009

Wrapper for Android Log class

While debugging an Android application, I realized that the ability to access log entries with 'logcat' beyond some OS defined cutoff was not possible, there were no options to write your log entries the SD card, so I put together a quick wrapper class that is already useful in its first incarnation here.

To use this class, drop it into your android package and comment out the import statements in your classes where you want the log entries to be written to a file. Java will pick up this copy of the Log class which in turn just forwards the entry to the Android logger. Next set the log file directory to point to the dir on the sdcard for your application then add the correct package name and you''re ready to go.

Note that the Log.e method includes a variant that takes a throwable. This method will write a stack trace to the log file for you.

Much more can be added here. What would you like to add?

/**
* Android Log class wrapper that writes all of your log entries
* to a log file on the sdcard
*/

//package com.MyApp

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

/**
* @author jos
*
*/
public class Log {
static File logFile = new File("/sdcard/myApp/" + Long.toString((new Date()).getTime()) + ".log");
static OutputStreamWriter osw = null;

static {
try {
FileOutputStream fis = new FileOutputStream(logFile);
osw = new OutputStreamWriter(fis);
} catch (Exception e){
android.util.Log.e("Logwrapper", "failed to open log file!");
}
}
static public int d(String t, String m) {
writeLog("D", t, m);
return android.util.Log.d(t, m);
}

static public int e(String t, String m, Throwable tr) {
writeLog("E", t, m);
writeLog(android.util.Log.getStackTraceString(tr));
return android.util.Log.e(t, m, tr);
}

static public int e(String t, String m) {
writeLog("E", t, m);
return android.util.Log.e(t, m);
}
static public int i(String t, String m) {
writeLog("i", t, m);
return android.util.Log.i(t, m);
}
static public int w(String t, String m) {
writeLog("w", t, m);
return android.util.Log.w(t, m);
}
static public int v(String t, String m) {
writeLog("V", t, m);
return android.util.Log.v(t, m);
}

private static void writeLog(String type, String tag, String m) {
writeLog(type + "/" + tag + "\t" + m + "\n");
}

private static void writeLog(String s) {
try {
osw.write(s);
osw.flush();
} catch (Exception e) {}
}
}