Android调试源码正确姿势打开ALOGV

      Android调试源码正确姿势打开ALOGV



前言

  当我沉浸在Android C++的世界中,准备通过其相关的ALOGV日志显示出来的时候,却发现怎么在logcat里面也找不到相关的日志,也许对Android ALOG日志有一定了解的会说实在不行通过ALOGD,ALOGW,ALOGE显示出来不就好了。这个是可以做到,但是不能通过相关的宏进行控制不是十分友好,而且如果Android原来的ALOGV打印的很多,难不成一个个的去修改。在本篇章我将带领打过彻底了解ALOGV的控制机制。

注意:ALOG日志等级的优先级秉承如下的顺序:

ALOGV < ALOGD < ALOGW < ALOGE



一.ALOGV控制相关代码

  ALOG相关定义在system/core/include/log/log.h里面,具体如下:

#ifndef LOG_NDEBUG
#ifdef NDEBUG
#define LOG_NDEBUG 1
#else
#define LOG_NDEBUG 0
#endif
#endif

/*
 * This is the local tag used for the following simplified
 * logging macros.  You can change this preprocessor definition
 * before using the other macros to change the tag.
 */
#ifndef LOG_TAG
#define LOG_TAG NULL
#endif


#ifndef ALOGV
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#if LOG_NDEBUG
#define ALOGV(...) do { if (0) { __ALOGV(__VA_ARGS__); } } while (0)
#else
#define ALOGV(...) __ALOGV(__VA_ARGS__)
#endif
#endif

#ifndef ALOGD
#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#endif

#ifndef ALOGW
#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
#endif


#ifndef ALOGE
#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
#endif

通过上面的源码我们发现,ALOGV主要受LOG_NDEBUG和LOG_NDEBUG的控制,并且假如你没有定义LOG_TAG 该头文件提供一个默认的为NULL。



二.ALOGV日志打开万能方法

  好了,对于原理分析清楚了,那么我们要来讲讲万能方法了,这里我们以zygote进程为例说明,其代码路径在frameworks/base/cmds/app_process/app_main.cpp中,我们想要打印出zygote启动传入的参数,添加如下调试信息:

int main(int argc, char* const argv[])
{
	......
	    if (1) {
      String8 argv_String;
      for (int i = 0; i < argc; ++i) {
        argv_String.append("\"");
        argv_String.append(argv[i]);
        argv_String.append("\" ");
      }
      ALOGV("app_process main with argv: %s", argv_String.string());
    }

	......
}

这里我们可以直接在app_main.cpp加上如下代码,就可以打印出所有的ALOGV信息了,同理也可以扩展到其它的模块上面:

#define LOG_TAG "appproc"
#undef NDEBUG
#define LOG_NDEBUG   0

相关的打印日志如下:

06-04 15:39:00.834  2901  2901 V appproc : app_process main with argv: "-Xzygote" "/system/bin" "--zygote" "--start-system-server" "--socket-name=zygote" 
06-04 15:39:16.532  3331  3331 V appproc : app_process main with argv: "/system/bin" "com.android.commands.settings.SettingsCmd" "get" "secure" "bluetooth_address" 


结语

  好了,Android调试源码正确姿势打开ALOGV就这么多了,终极大法就是在你所要打印的C++模块的起始代码端加入如下代码段,就万事OK了。

#define LOG_TAG "appproc"
#undef NDEBUG
#define LOG_NDEBUG   0

猜你喜欢

转载自blog.csdn.net/tkwxty/article/details/106550201