Friday, May 4, 2012

Debug Android App using Log

Debugging during development process always play a key role, so lots of developer use logging. Android provides us a great interface while dealing with logcat. The problem I saw with few developers, they simply use the log for debugging and never remove their log statements before creating final apk & which result in decreased application performance.

To avoid this situation, you can create a custom log class & can control the amount of information visible in logcat. The CustomLogger class is as follow:-

public class CustomLogger {
     
        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);
                }
        }

}

This class helps you to hide all the debug calls automatically from logcat in final apk. Using this CustomLogger class 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. This class is simply wrapping the calls to the android Log class. The rest of your application can simply reference CustomLogger.d("TAG NAME", "DEBUG MESSAGE"); before displaying any debug info it will check for the return boolean variable from Log.isLoggable() method. If the device/emulator running the app has the log level set to debug then only message will appear.

As you know after SDK Tools, Revision 8 (December 2010) - Support for a true debug build. Developers no longer need to add the android:debuggable attribute to the tag in the manifest — the build tools add the attribute automatically.