Ryan Ryan - 5 months ago 17
Android Question

Flexible enable/disable logging in Android app

For performance wise, some people suggest use the following method, e.g.

public class MyActivity extends Activity {

private static final String TAG = "MyApp";
private static final boolean D = true;

@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "MyActivity.onCreate debug message"); }


But this is non-senese when are working on a large project, because when you debug, you need to update many files for the
debug
flag, are there any better method?

Answer

You can check the DEBUG boolean in your BuildConfig:

if (BuildConfig.DEBUG) {
    // Do what you need
}

Or else, you can have a debug variable, but instead or keeping it in every activity, declare it in you Application class, and check it's value whenever you need.

If your purpose of that variable is for logging, is a good practice to wrap your loggings into another class, which checks the DEBUG variable:

public class LogUtils {
    public static void LOGD(final String tag, String message) {
        if (BuildConfig.DEBUG) {
            Log.d(tag, message);
        }
    }

    public static void LOGV(final String tag, String message) {
        if (BuildConfig.DEBUG) {
            Log.v(tag, message);
        }
    }

    public static void LOGI(final String tag, String message) {
        if (BuildConfig.DEBUG) {
            Log.i(tag, message);
        }
    }

    public static void LOGW(final String tag, String message) {
        if (BuildConfig.DEBUG) {
            Log.w(tag, message);
        }
    }

    public static void LOGE(final String tag, String message) {
        if (BuildConfig.DEBUG) {
            Log.e(tag, message);
        }
    }

}

Then, make log calls to this class:

LogUtils.LOGD(TAG, "MyActivity.onCreate debug message");
Comments