How to remove all debug logging calls before building the release version of an Android app?

前端 未结 27 1475
有刺的猬
有刺的猬 2020-11-22 07:39

According to Google, I must \"deactivate any calls to Log methods in the source code\" before publishing my Android app to Google Play. Extract from section 3 of th

相关标签:
27条回答
  • 2020-11-22 08:32

    I highly suggest using Timber from Jake Wharton

    https://github.com/JakeWharton/timber

    it solves your issue with enabling/disabling plus adds tag class automagically

    just

    public class MyApp extends Application {
    
      public void onCreate() {
        super.onCreate();
        //Timber
        if (BuildConfig.DEBUG) {
          Timber.plant(new DebugTree());
        }
        ...
    

    logs will only be used in your debug ver, and then use

    Timber.d("lol");
    

    or

    Timber.i("lol says %s","lol");
    

    to print

    "Your class / msg" without specyfing the tag

    0 讨论(0)
  • 2020-11-22 08:35

    All good answers, but when I was finished with my development I didn´t want to either use if statements around all the Log calls, nor did I want to use external tools.

    So the solution I`m using is to replace the android.util.Log class with my own Log class:

    public class Log {
        static final boolean LOG = BuildConfig.DEBUG;
    
        public static void i(String tag, String string) {
            if (LOG) android.util.Log.i(tag, string);
        }
        public static void e(String tag, String string) {
            if (LOG) android.util.Log.e(tag, string);
        }
        public static void d(String tag, String string) {
            if (LOG) android.util.Log.d(tag, string);
        }
        public static void v(String tag, String string) {
            if (LOG) android.util.Log.v(tag, string);
        }
        public static void w(String tag, String string) {
            if (LOG) android.util.Log.w(tag, string);
        }
    }
    

    The only thing I had to do in all the source files was to replace the import of android.util.Log with my own class.

    0 讨论(0)
  • 2020-11-22 08:37

    Easy with kotlin, just declare a few top level functions

    val isDebug: Boolean
        get() = BuildConfig.DEBUG
    
    fun logE(tag: String, message: String) {
        if (isDebug) Log.e(tag, message)
    }
    
    fun logD(tag: String, message: String) {
        if (isDebug) Log.d(tag, message)
    }
    
    0 讨论(0)
提交回复
热议问题