首页 - 安全 - 如何在andorid native layer中加log function.【转】

如何在andorid native layer中加log function.【转】

2023-09-05 16:14
-->

本文转载自:https://www.gsm-guard.net/powq2009/article/details/39667105

在开发Android一些应用或是链接库, 在程序代码中埋一些log是一定有需要的, 因为谁也无法保证自己所写出来的程序一定没有问题, 而log机制正是用来追踪bug途径的一种常用的方法. 在andorid中提供了logcat的机制来作log的目的, 在javalayer有logcat class可以用,哪在nativelayer呢? 从android platform source code中不难发现, 其实在nativelayer也有一些跟logcat相关的log用法. 以下就从目前的aosp的source code中整理出来的log用法.

Header system/core/include/cutils/log.h
Library www.gsm-guard.net
Example 1. add shared lib to LOCAL_SHARED_LIBRARIES in www.gsm-guard.net
LOCAL_SHARED_LIBRARIES += libcutils
2. add log define and include the header file in the top of the source file.
#define LOG_NDEBUG 0
#define LOG_TAG "XXX"
#include
3. Use the function as below to print log in logcat.
ALOGV
ALOGD
ALOGI
ALOGW
ALOGE

Header frameworks/native/include/utils/Log.h
Library www.gsm-guard.net
Example 1. add shared lib to LOCAL_SHARED_LIBRARIES in www.gsm-guard.net
LOCAL_SHARED_LIBRARIES += libutils
2. add log define and include the header file in the top of the source file.
#define LOG_NDEBUG 0
#define LOG_TAG "XXX"
#include
3. Use the function as below to print log in logcat.
ALOGV
ALOGD
ALOGI
ALOGW
ALOGE

从这里会发现, 第一个跟第二个用法除了link的sharedlibrary 和 include的header file不一样之外, 其他的logfunction 都一样. 其实这个原因很明显就是android的log机制重构过,www.gsm-guard.net 提供的log function 是比较早期的,后来多了一个新的www.gsm-guard.net提供新的logfunction, 然而在更新log机制之下,又不能影响早就用旧的log机制的module, 所以就把旧的www.gsm-guard.net跟新的www.gsm-guard.net作结合, 始其使用旧log机制可以导到新的log机制.

Header system/core/include/android/log.h
Library None
Example 1. Define customize Log tag in the top of the source file.
#define LOG_XXX_TAG "XXX"
2. Define customize Log function by __android_log_print
#define LOGV(...) __android_log_print( ANDROID_LOG_VERBOSE, LOG_XXX_TAG, __VA_ARGS__ )
#define LOGD(...) __android_log_print( ANDROID_LOG_DEBUG, LOG_XXX_TAG, __VA_ARGS__ )
#define LOGI(...) __android_log_print( ANDROID_LOG_INFO, LOG_XXX_TAG, __VA_ARGS__ )
#define LOGW(...) __android_log_print( ANDROID_LOG_WARN, LOG_XXX_TAG, __VA_ARGS__ )
#define LOGE(...) __android_log_print( ANDROID_LOG_ERROR, LOG_XXX_TAG, __VA_ARGS__ )

最后一个用法跟前两个的用法不一样的地方是Log tag可以自己define, 而前两个的Logtag只能define LOG_TAG 以及一定要defineLOG_NDEBUG 0, 这样加入的log function才有作用.说白点, 第三种用法比较不会被制约化.自己的log自己作,log的开关控制自己定. 优点是客制化佳, 缺点是不统一.

-->