Friday, April 08, 2011

How to set automatic debug flag in Android for Logging

In my old method, I prefer to copy/paste follow code into each module.

static public boolean DEBUG_MODE = true; static public String DEBUG_MODEL_NAME = "your_module_name"; static public String DEBUG_TAG = "your_debug_tag"; static public void logD(String message){ if(DEBUG_MODE == false) return; Log.d(DEBUG_TAG, DEBUG_MODEL_NAME + " : " + message); } static public void logI(String message) { if(DEBUG_MODE == false) return; Log.i(DEBUG_TAG, DEBUG_MODEL_NAME + " : " + message); } static public void logE(String message) { if(DEBUG_MODE == false) return; Log.e(DEBUG_TAG, DEBUG_MODEL_NAME + " : " + message); }

This method is sharp, and you can debug each method. When you want to release, simply replace all "static public boolean DEBUG_MODE = true" to "static public boolean DEBUG_MODE = false" by Eclipse.



However, if your logging message is not so much, you can control logger flag in this way, more conveniently and efficiently.







PackageInfo packageInfo = ... // get package info for your context

int flags = packageInfo.applicationInfo.flags;

boolean DEBUG_MODE = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;




now you can control debug flag in AndroidManifest.xml's "Debuggable" flag, automatically.