Thursday, 12 January 2012

Android Custom Logging - Enable/Disable Logs

Part of the Android 'Preparing for Release' onto the Android Market is to remove all Log messages and have the android:debuggable="false" in the manifest file. This is outlined here in the section called 'Turn off logging and debugging'.

Removing all logs can be difficult, however you might still decide, that's okay I will comment all my logs out! This would not be a bad idea but its not the most efficient by far, an alternative is to add 'if' statements for every Log in your app that points to a global boolean flag...however that is also not easy with lots of Log calls.

The solution that I adopted was create a wrapper class around the Log class called MyLog. Then by replacing all instances of Log in my Android app with MyLog, I was then able to have an 'on off' switch for Log calls...the code looked a little bit like this:
import android.util.Log;

public class MyLog
{
 
 private MyLog()
 {
  
 }

 private static boolean LOG_ENABLED = true;

 public static void d(String tag, String msg)
 {
  if (LOG_ENABLED)
   Log.d(tag, msg);
 }
 
 public static void d(String tag, String msg, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.d(tag, msg, tr);
 }

 public static void e(String tag, String msg)
 {
  if (LOG_ENABLED)
   Log.e(tag, msg);
 }

 public static void e(String tag, String msg, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.e(tag, msg, tr);
 }

 public static void i(String tag, String msg)
 {
  if (LOG_ENABLED)
   Log.i(tag, msg);
 }

 public static void i(String tag, String msg, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.i(tag, msg, tr);
 }
 
 public static void v(String tag, String msg)
 {
  if (LOG_ENABLED)
   Log.v(tag, msg);
 }
 
 public static void v(String tag, String msg, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.v(tag, msg, tr);
 }
 
 public static void w(String tag, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.w(tag, tr);
 }
 
 public static void w(String tag, String msg, Throwable tr)
 {
  if (LOG_ENABLED)
   Log.w(tag, msg, tr);
 }

 public static void w(String tag, String msg)
 {
  if (LOG_ENABLED)
   Log.w(tag, msg);
 }
 
}
Example Log from MyLog:
MyLog.v("Tag","Hello World!");
As you may have guessed to turn the logs off you change the code to LOG_ENABLED = false, this allows you to easily switch between development and publishing versions of the code.

No comments:

Post a Comment