Lots of Android developers use logging during the development of their apps. Android provides a great interface to work with the systems logcat. Unfortunately a majority of developers don’t turn down their logging when they go to ship their app to the market. This short post demonstrates how to wrap calls to the Log class to control the amount of information visible in logcat.
The Android Log class contains numerous methods to print debugging information to the logcat utility. Logcat is visible in the debug perspective in Eclipse or by running adb logcat on the command line.
The short class below is a sample showing log level checking prior to printing to the log.
import android.util.Log;
public class MyLog {
public static void d(String tag, String msg) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (Log.isLoggable(tag, Log.INFO)) {
Log.i(tag, msg);
}
}
public static void e(String tag, String msg) {
if (Log.isLoggable(tag, Log.ERROR)) {
Log.e(tag, msg);
}
}
public static void v(String tag, String msg) {
if (Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, msg);
}
}
public static void w(String tag, String msg) {
if (Log.isLoggable(tag, Log.WARN)) {
Log.w(tag, msg);
}
}
}
To summarize the preceding code, the MyLog class is simply wrapping the calls to the android Log class. The rest of your application can simply reference MyLog.d(“MyApp”, “Sample debug message”); and if the device/emulator running the app has the log level set to debug the message will appear. The benefit here is you won’t have to worry about removing print lines or maintaining variables for levels that you might forget to change before building your release apk.
Changing the log level on device is actually very simple. Simply run adb shell setprop log.tag.<YOUR_LOG_TAG> <LEVEL>
There you have it, this is only a small sample of what you can do meant to get you started. This code is compatible with Android since API Level 1. I recommend reading through the Log javadoc here for more details about the Logging capabilities on Android.