1. 程式人生 > >如何在andorid native layer中加log function.【轉】

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

本文轉載自:https://blog.csdn.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 libcutils.so
Example 1. add shared lib to LOCAL_SHARED_LIBRARIES in Android.mk
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 <cutils/log.h>
3. Use the function as below to print log in logcat.
ALOGV
ALOGD
ALOGI
ALOGW
ALOGE


Header frameworks/native/include/utils/Log.h
Library libutils.so
Example 1. add shared lib to LOCAL_SHARED_LIBRARIES in Android.mk
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 <utils/Log.h>
3. Use the function as below to print log in logcat.
ALOGV
ALOGD
ALOGI
ALOGW
ALOGE


從這裡會發現, 第一個跟第二個用法除了link的sharedlibrary 和 include的header file不一樣之外, 其他的logfunction 都一樣. 其實這個原因很明顯就是android的log機制重構過,libutils.so 提供的log function 是比較早期的,後來多了一個新的libcutils.so提供新的logfunction, 然而在更新log機制之下,又不能影響早就用舊的log機制的module, 所以就把舊的libutils.so跟新的libcutils.so作結合, 始其使用舊log機制可以導到新的log機制.

 

Header system/core/include/android/log.h
Library None
Example 1. Define customize Log tag in the top of the source file.
<span style="white-space:pre"> </span>#define LOG_XXX_TAG "XXX"
2. Define customize Log function by __android_log_print
<span style="white-space:pre"> </span>#define LOGV(...) __android_log_print( ANDROID_LOG_VERBOSE, LOG_XXX_TAG, __VA_ARGS__ )
<span style="white-space:pre"> </span>#define LOGD(...) __android_log_print( ANDROID_LOG_DEBUG, LOG_XXX_TAG, __VA_ARGS__ )
<span style="white-space:pre"> </span>#define LOGI(...) __android_log_print( ANDROID_LOG_INFO, LOG_XXX_TAG, __VA_ARGS__ )
<span style="white-space:pre"> </span>#define LOGW(...) __android_log_print( ANDROID_LOG_WARN, LOG_XXX_TAG, __VA_ARGS__ )
<span style="white-space:pre"> </span>#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的開關控制自己定. 優點是客製化佳, 缺點是不統一.