你知道Log.isLoggable

阅读更多
我们可以通过Log.isLoggable来动态开关log的输出。
http://androidxref.com/8.1.0_r33/xref/frameworks/base/core/java/android/util/Log.java
android.util.Log中的isLoggable方法解析:
    /**
     * Checks to see whether or not a log for the specified tag is loggable at the specified level.
    *
     *  The default level of any tag is set to INFO. This means that any level above and including
     *  INFO will be logged. Before you make any calls to a logging method you should check to see
     *  if your tag should be logged. You can change the default level by setting a system property:
     *      'setprop log.tag.<YOUR_LOG_TAG> <LEVEL>'
     *  Where level is either VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT, or SUPPRESS. SUPPRESS will
     *  turn off all logging for your tag. You can also create a local.prop file that with the
     *  following in it:
     *      'log.tag.<YOUR_LOG_TAG>=<LEVEL>'
     *  and place that in /data/local.prop.
     *
     * @param tag The tag to check.
     * @param level The level to check.
     * @return Whether or not that this is allowed to be logged.
     * @throws IllegalArgumentException is thrown if the tag.length() > 23
     *         for Nougat (7.0) releases (API <= 23) and prior, there is no
     *         tag limit of concern after this API level.
     */

public static native boolean isLoggable(String tag, int level);
其默认的等级是INFO,只有INFO以上的级别可以输出,若我们需要修改其等级,可以通过adb shell setprop TAG LEVEL这种方法来调整,或者是修改local.prop来设置

其应用可以参考
http://androidxref.com/8.1.0_r33/xref/packages/apps/DeskClock/src/com/android/deskclock/LogUtils.java
63        /**
         * Log everything for debug builds or if running on a dev device.
         */
        public final static boolean DEBUG = BuildConfig.DEBUG
                || "eng".equals(Build.TYPE)
                || "userdebug".equals(Build.TYPE);

        public final String logTag;

        public Logger(String logTag) {
            this.logTag = logTag;
        }

        public boolean isVerboseLoggable() { return DEBUG || Log.isLoggable(logTag, Log.VERBOSE); }
        public boolean isDebugLoggable() { return DEBUG || Log.isLoggable(logTag, Log.DEBUG); }
        public boolean isInfoLoggable() { return DEBUG || Log.isLoggable(logTag, Log.INFO); }
        public boolean isWarnLoggable() { return DEBUG || Log.isLoggable(logTag, Log.WARN); }
        public boolean isErrorLoggable() { return DEBUG || Log.isLoggable(logTag, Log.ERROR); }
        public boolean isWtfLoggable() { return DEBUG || Log.isLoggable(logTag, Log.ASSERT); }


比如:
public static final String TAG = "Test";
public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

public void onCreate(){
    if (DEBUG){
        Log.d(TAG, "onCreate");
    }
}

adb shell setprop log.tag.Test D
若是App,则退出APP,重新进入,即可打印Log,若是Framework,则需要执行adb shell stop
adb shell start


你可能感兴趣的:(android)