简体   繁体   English

Android的调试日志在运行时真的被剥离了吗?

[英]are Android's debug logs really stripped at runtime?

Android documentation ( http://developer.android.com/reference/android/util/Log.html ) says: Android文档( http://developer.android.com/reference/android/util/Log.html )说:

Verbose should never be compiled into an application except during development. 除了在开发期间,不应该将详细编译到应用程序中。 Debug logs are compiled in but stripped at runtime. 调试日志在运行时编译但被剥离。 Error, warning and info logs are always kept 始终保留错误,警告和信息日志

I just did a test. 我刚做了一个测试。 In my activity I wrote: 在我的活动中,我写道:

private static String test(String what) {
    Log.e("test", "I am called with argument: " + what);
    return what;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.v("test", "log level: " + test("v"));
    Log.d("test", "log level: " + test("d"));
    Log.i("test", "log level: " + test("i"));
    Log.w("test", "log level: " + test("w"));
    Log.e("test", "log level: " + test("e"));
}

I exported my project as an apk file, then I installed this apk on my phone. 我将我的项目导出为apk文件,然后我在手机上安装了这个apk。 I run this application on my phone, then I looked at logs. 我在手机上运行这个应用程序,然后查看了日志。 There I saw that the function test was called all five times and all five calls to Log.something functions resulted in its text being written to logs. 在那里,我看到函数测试被调用了五次,所有五次调用Log.something函数导致其文本被写入日志。

So are Log.d calls really stripped at runtime? Log.d调用在运行时是否真的被剥离了?

No. You have to do this yourself. 不,你必须自己做。 You can make your own Log.d wrapper like this: 您可以像这样制作自己的Log.d包装器:

public static void debug(String tag, String msg) {
    if (BuildConfig.DEBUG) {
        Log.d(tag, msg);
    }
}

This issue was reported here and a solution was provided in ADT 17.0.0 in Mar 2012 此问题已在此处报告并在2012年3月的ADT 17.0.0中提供了解决方案

Added a feature that allows you to run some code only in debug mode. 添加了一项功能,允许您仅在调试模式下运行某些代码。 Builds now generate a class called BuildConfig containing a DEBUG constant that is automatically set according to your build type. Builds现在生成一个名为BuildConfig的类,其中包含一个DEBUG常量,该常量根据您的构建类型自动设置。 You can check the (BuildConfig.DEBUG) constant in your code to run debug-only functions. 您可以检查代码中的(BuildConfig.DEBUG)常量以运行仅调试函数。

The best way to remove logs is probably achieved with ProGuard 使用ProGuard可能会实现删除日志的最佳方法

Check this question ' Android Proguard, removing all Log statements and merging packages ' 检查这个问题' Android Proguard,删除所有日志语句和合并包 '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM