版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010479969/article/details/78193747
背景:我们大多数情况不希望我们的log在应用上线依然被看到,所以我们可以采用以下的几种方式来限制住。
方法一
封装一个类两个作用:
1).通过一个debug开关决定是否输出log
2).可以决定是否写入文件
但这样还是有问题,就是我反编译代码之后,能看到log,方便别人破解代码,就出现了
方法二
在每一句log上都增加debug开关,debug开关同一控制
if(debug){
Log.v(***,***);
}
这样确实无法打印出来了,但是比较麻烦,所以还有
方法三
通过混淆来去掉log
在混淆文件中加入下面的代码:
-assumenosideeffects class android.util.Log {
public static *** v(...);
public static *** d(...);
public static *** i(...);
public static *** w(...);
public static *** e(...);
}
就将我们的所有log全部优化没了,但是不能配置: -dontoptimize还有一种场景是我们需要的时候,让他打印,不需要的时候,不让打印。
方法四:
这放方法一般做过原生系统开发的都知道,正常是打印不出来的,当需要打印的时候,使用下面命令就可以打印了,不输入的手机不会打印出来。
adb shell setprop log.tag.DD VERBOSE
直接拷贝一段源码,大家自己看吧
public class Logs {
public static final String TAG = "DD";
public static void call(Object self, String method, Object... args) {
call(Log.DEBUG, self, method, args);
}
public static void call(int priority, Object self, String method, Object... args) {
if (Log.isLoggable(TAG, priority)) {
Log.d(
TAG,
String.format("Invoking %s.%s(%s)", self.getClass().getSimpleName(), method,
TextUtils.join(", ", args)));
}
}
public static void log(int priority, String msg) {
if (Log.isLoggable(TAG, priority)) {
Log.println(priority, TAG, msg);
}
}
public static void log(int priority, Throwable e) {
if (Log.isLoggable(TAG, priority)) {
Log.println(priority, TAG, Log.getStackTraceString(e));
}
}
public static void log(int priority, Throwable e, String msg) {
if (Log.isLoggable(TAG, priority)) {
Log.println(priority, TAG, msg + '\n' + Log.getStackTraceString(e));
}
}
public static void logfmt(int priority, String format, Object... args) {
if (Log.isLoggable(TAG, priority)) {
Log.println(priority, TAG, String.format(format, args));
}
}
public static void logfmt(int priority, Throwable e, String format, Object... args) {
if (Log.isLoggable(TAG, priority)) {
Log.println(priority, TAG, String.format(format, args) + '\n' + Log.getStackTraceString(e));
}
}
private Logs() {}
}