LOG 是開發過程中無所不在的幫手,既能用於除錯,也能在產品維運時記錄事件。Android 提供了一套輕便的日誌機制,值得花點時間了解它的用法與原理。
標準 Linux 核心開發中使用 printk,功能近似 printf,但多了等級概念,訊息會寫入 /proc/kmsg,用 cat /proc/kmsg 即可查看:
#define KERN_EMERG "<0>" /* system is unusable */ #define KERN_ALERT "<1>" /* action must be taken immediately */ #define KERN_CRIT "<2>" /* critical conditions */ #define KERN_ERR "<3>" /* error conditions */ #define KERN_WARNING "<4>" /* warning conditions */ #define KERN_NOTICE "<5>" /* normal but significant condition */ #define KERN_INFO "<6>" /* informational */ #define KERN_DEBUG "<7>" /* debug-level messages */
Android 在核心中實作了一個輕量級的 logger 裝置驅動,搭配使用者空間的 logcat 工具,就能方便地追蹤與除錯程式。
C/C++ 端的介面是以巨集形式提供,等級定義在 system/core/include/android/log.h:
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT, /* only for SetMinPriority() */
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
} android_LogPriority;
為了方便,system/core/include/cutils/log.h 又包了一層巨集:
#define LOGV(...) ((void)LOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) #define LOGD(...) ((void)LOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) #define LOGI(...) ((void)LOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) #define LOGW(...) ((void)LOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) #define LOGE(...) ((void)LOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
要用時,包含標頭檔並連結 liblog.so 即可:
#define LOG_TAG "XX_LOG_TAG" // 這裡定義輸出的 TAG #include <cutils/log.h>
import android.util.Log; private static final String TAG = "XX_LOG_TAG"; Log.e(TAG, "This is the error log printed by Log.i in android user space.");
實務上建議養成兩個習慣:每個類別定義自己的 TAG,方便用 logcat 的过滤條件篩選;正式版本則關閉除錯層級的輸出,避免效能與個資上的困擾。