Logging in any type of software is a useful tool to debug and improve your software. Typically you’ll have different types of stuff you want to log: errors, information, traceing etc. So most logging systems have a concept of levels that allow you to specify how important a message is, so that at a later time you can enable a certain type of logging to inspect.
In Android it is handled by the Log class. It too allows for runtime configuration of loggers and it involves setting Android system properties using the setprop command, which is nice if you are building an app as part of the OS but maybe overkill or even clunky if you just want to create your next great app. And what if you don’t want your shipping app to have any logging whatsoever? You certainly want it during development, trust me :) Well enter this little utility class:
package com.neenbedankt.rainydays.util;
public class Logging {
public static final boolean LOGV = true;
public static final boolean LOGD = false || LOGV;
public static final boolean LOGI = false || LOGD;
public static final boolean LOGW = false || LOGI;
public static final boolean LOGE = false || LOGW;
}
What this does is setting some flags that indicate what level of logging you want. If you want all logging, just set LOGV to true. If you only want the “info” level and up just enable info. Easy! Now you still have to reference this from your code like this:
// you can also use a static import to drop the Logging part...
if (Logging.LOGD) {
Log.d(TAG, 'This is my debug statement');
}
Tip: you can setup an Eclipse template to generate these kinds of code blocks very fast.
Now the beauty of this all is that since the LOGD variable is a static final (a constant) the compiler will strip out the entire if statement if the LOGD variable is false, hence no logging in your final app and no bytecode generated for it either.
So by introducing a simple class and wrapping the log statements in an if block you’ll still be able to enable particular levels of logging, while in your shipping product the logging is stripped out.