Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Logcat 源碼剖析:從打開設備到輸出日誌

編輯:關於 Android 程式設計

Logcat 是 Android 內建的日誌工具,開發者在主機端執行 adb logcat 就能看到模擬器或真機上的日誌輸出。它的參數組合非常豐富,源碼量 correspondingly 也不小。本文不追求逐行覆蓋,而是沿著一條主線走一遍:打開日誌設備文件 → 讀取日誌記錄 → 格式化並輸出。理解了這條主幹,其餘分支自然觸類旁通。

源碼位於 system/core/logcat 目錄,只有一個 logcat.cpp 文件;編譯產物在 out/target/product/generic/system/bin 下,模擬器中可以在 /system/bin 看到 logcat。

一、核心數據結構

兩個結構體撐起了整個流程:queued_entry_t 代表一條日誌記錄,log_device_t 代表一個日誌設備的上下文,每個設備上下文內部掛著一條 queued_entry_t 隊列。

struct queued_entry_t {
    union {
        unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
        struct logger_entry entry __attribute__((aligned(4)));
    };
    queued_entry_t* next;

    queued_entry_t() {
        next = NULL;
    }
};

struct log_device_t {
    char* device;
    bool binary;
    int fd;
    bool printed;
    char label;

    queued_entry_t* queue;
    log_device_t* next;

    log_device_t(char* d, bool b, char l) {
        device = d;
        binary = b;
        label = l;
        queue = NULL;
        next = NULL;
        printed = false;
    }

    void enqueue(queued_entry_t* entry) {
        if (this->queue == NULL) {
            this->queue = entry;
        } else {
            queued_entry_t** e = &this->queue;
            while (*e && cmp(entry, *e) >= 0) {
                e = &((*e)->next);
            }
            entry->next = *e;
            *e = entry;
        }
    }
};

其中 LOGGER_ENTRY_MAX_LEN 與 struct logger_entry 定義在 system/core/include/cutils/logger.h:

struct logger_entry {
    __u16      len;   /* length of the payload */
    __u16      __pad; /* no matter what, we get 2 bytes of padding */
    __s32      pid;   /* generating process's pid */
    __s32      tid;   /* generating process's tid */
    __s32      sec;   /* seconds since Epoch */
    __s32      nsec;  /* nanoseconds */
    char       msg[0]; /* the entry's payload */
};

#define LOGGER_ENTRY_MAX_LEN     (4*1024)

設備上下文通過 next 指針串成鏈表,設備內部的日誌記錄同樣用 next 串成隊列。Android 日誌系統共有三個設備文件:/dev/log/main、/dev/log/events 和 /dev/log/radio。

為什麼隊列要按時間戳排序? 從 enqueue 的實現可以看出,插入新記錄時會從隊頭開始尋找第一個時間戳更大的位置,把新記錄插在它前面,於是整個隊列始終是「舊在前、新在後」。比較函數很直觀:

static int cmp(queued_entry_t* a, queued_entry_t* b) {
    int n = a->entry.sec - b->entry.sec;
    if (n != 0) {
        return n;
    }
    return a->entry.nsec - b->entry.nsec;
}

這樣排序是為了支持 -t <count> 參數——只顯示最新的 count 條記錄。既然隊頭最舊,那麼需要丟棄時只要從隊頭開始扔即可,非常省事。默認情況下則全部輸出。

二、打開日誌設備文件

入口函數 main 承擔了命令行解析、設備初始化和輸出初始化。假設我們執行的是不帶任何參數的 logcat,先看設備上下文的創建:

if (!devices) {
    devices = new log_device_t(strdup("/dev/"LOGGER_LOG_MAIN), false, 'm');
    android::g_devCount = 1;
    int accessmode =
            (mode & O_RDONLY) ? R_OK : 0
            | (mode & O_WRONLY) ? W_OK : 0;
    // only add this if it's available
    if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
        devices->next = new log_device_t(strdup("/dev/"LOGGER_LOG_SYSTEM), false, 's');
        android::g_devCount++;
    }
}

沒有指定設備時,默認創建 main 設備上下文;若系統中還存在 /dev/log/system,則一併加入。兩個宏同樣定義在 logger.h 中:

#define LOGGER_LOG_MAIN      "log/main"
#define LOGGER_LOG_SYSTEM    "log/system"

值得注意的是,Logger 驅動默認並不創建 /dev/log/system,所以大多數情況下只有 main 一個設備。

接著初始化輸出目標:

static void setupOutput()
{
    if (g_outputFileName == NULL) {
        g_outFD = STDOUT_FILENO;
    } else {
        struct stat statbuf;

        g_outFD = openLogFile (g_outputFileName);

        if (g_outFD < 0) {
            perror ("couldn't open output file");
            exit(-1);
        }

        fstat(g_outFD, &statbuf);

        g_outByteCount = statbuf.st_size;
    }
}

也就是說,帶 -f <filename> 時寫文件,否則寫標準輸出。

然後真正打開設備,並順便處理「清空日誌」「查看緩衝區大小」這兩類一次性任務:

dev = devices;
while (dev) {
    dev->fd = open(dev->device, mode);
    if (dev->fd < 0) {
        fprintf(stderr, "Unable to open log device '%s': %s\n",
                dev->device, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (clearLog) {
        int ret;
        ret = android::clearLog(dev->fd);
        if (ret) {
            perror("ioctl");
            exit(EXIT_FAILURE);
        }
    }

    if (getLogSize) {
        int size, readable;

        size = android::getLogSize(dev->fd);
        if (size < 0) {
            perror("ioctl" );
            exit(EXIT_FAILURE);
        }

        readable = android::getLogReadableSize(dev->fd);
        if (readable < 0) {
            perror("ioctl");
            exit(EXIT_FAILURE);
        }

        printf("%s: ring buffer is %dKb (%dKb consumed), "
               "max entry is %db, max payload is %db\n", dev->device,
               size / 1024, readable / 1024,
               (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
    }

    dev = dev->next;
}

這三個操作本質上都是 ioctl:

static int clearLog(int logfd)
{
    return ioctl(logfd, LOGGER_FLUSH_LOG);
}

/* returns the total size of the log's ring buffer */
static int getLogSize(int logfd)
{
    return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
}

/* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
static int getLogReadableSize(int logfd)
{
    return ioctl(logfd, LOGGER_GET_LOG_LEN);
}

完成清空或查詢後任務即結束,程序直接退出;否則進入真正的讀取階段:

android::readLogLines(devices);

三、讀取日誌設備文件

readLogLines 是整個工具的心臟。由於可能同時打開多個設備,這裡用 select 來複用多路 I/O:

static void readLogLines(log_device_t* devices)
{
    log_device_t* dev;
    int max = 0;
    int ret;
    int queued_lines = 0;
    bool sleep = true;

    int result;
    fd_set readset;

    for (dev=devices; dev; dev = dev->next) {
        if (dev->fd > max) {
            max = dev->fd;
        }
    }

    while (1) {
        do {
            timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
            FD_ZERO(&readset);
            for (dev=devices; dev; dev = dev->next) {
                FD_SET(dev->fd, &readset);
            }
            result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
        } while (result == -1 && errno == EINTR);

        if (result >= 0) {
            for (dev=devices; dev; dev = dev->next) {
                if (FD_ISSET(dev->fd, &readset)) {
                    queued_entry_t* entry = new queued_entry_t();
                    /* NOTE: driver guarantees we read exactly one full entry */
                    ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
                    if (ret < 0) {
                        if (errno == EINTR) {
                            delete entry;
                            goto next;
                        }
                        if (errno == EAGAIN) {
                            delete entry;
                            break;
                        }
                        perror("logcat read");
                        exit(EXIT_FAILURE);
                    }
                    else if (!ret) {
                        fprintf(stderr, "read: Unexpected EOF!\n");
                        exit(EXIT_FAILURE);
                    }

                    entry->entry.msg[entry->entry.len] = '\0';

                    dev->enqueue(entry);
                    ++queued_lines;
                }
            }
        }
        /* ... 後續輸出邏輯見下文 ... */
next:
        ;
    }
}

幾個要點:

  • sleep 為 true 時 select 使用 NULL 超時(阻塞等待);為 false 時用 5ms 短超時輪一次,這是為了在「有數據可讀」和「無數據可讀」兩種狀態間做切換。
  • 驅動保證每次 read 恰好返回一條完整記錄,因此不需要自己處理粘包。
  • 讀到記錄後在 msg 末尾補 '\0',再 enqueue 進設備隊列,並累加 queued_lines。

讀完一批之後的處理分兩種情況:

if (result == 0) {
    // we did our short timeout trick and there's nothing new
    // print everything we have and wait for more data
    sleep = true;
    while (true) {
        chooseFirst(devices, &dev);
        if (dev == NULL) {
            break;
        }
        if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
            printNextEntry(dev);
        } else {
            skipNextEntry(dev);
        }
        --queued_lines;
    }

    // the caller requested to just dump the log and exit
    if (g_nonblock) {
        exit(0);
    }
} else {
    // print all that aren't the last in their list
    sleep = false;
    while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
        chooseFirst(devices, &dev);
        if (dev == NULL || dev->queue->next == NULL) {
            break;
        }
        if (g_tail_lines == 0) {
            printNextEntry(dev);
        } else {
            skipNextEntry(dev);
        }
        --queued_lines;
    }
}

result == 0 意味著短超時到點且沒有新數據,此時可以放心地把已讀出的記錄全部輸出,然後轉為阻塞等待。result > 0 說明還有新數據要讀,那就只處理「不是各隊列末位」的記錄,把每個設備隊列中最後一條留著,等下一輪再說——這樣做能保證多設備日誌按時間先後交錯輸出,不會因為忙著讀新數據而讓某個設備的舊記錄被憋住。

挑選輸出對象的 chooseFirst 就是找出隊頭時間戳最小的那個設備:

static void chooseFirst(log_device_t* dev, log_device_t** firstdev) {
    for (*firstdev = NULL; dev != NULL; dev = dev->next) {
        if (dev->queue != NULL && (*firstdev == NULL || cmp(dev->queue, (*firstdev)->queue) < 0)) {
            *firstdev = dev;
        }
    }
}

而丟棄記錄的 skipNextEntry 只是把隊頭摘下來 delete 掉:

static void skipNextEntry(log_device_t* dev) {
    maybePrintStart(dev);
    queued_entry_t* entry = dev->queue;
    dev->queue = entry->next;
    delete entry;
}

當 g_tail_lines(即 -t 指定的條數)為 0 時表示全部顯示;否則已進入隊列的行數超過它就丟棄最舊的,正好只留下最新 count 條。

四、輸出日誌內容

static void printNextEntry(log_device_t* dev) {
    maybePrintStart(dev);
    if (g_printBinary) {
        printBinary(&dev->queue->entry);
    } else {
        processBuffer(dev, &dev->queue->entry);
    }
    skipNextEntry(dev);
}

二進制模式直接把原始結構寫出去,不做任何解析:

void printBinary(struct logger_entry *buf)
{
    size_t size = sizeof(logger_entry) + buf->len;
    int ret;

    do {
        ret = write(g_outFD, buf, size);
    } while (ret < 0 && errno == EINTR);
}

我們更關心的是文本模式下的 processBuffer:

static void processBuffer(log_device_t* dev, struct logger_entry *buf)
{
    int bytesWritten = 0;
    int err;
    AndroidLogEntry entry;
    char binaryMsgBuf[1024];

    if (dev->binary) {
        err = android_log_processBinaryLogBuffer(buf, &entry, g_eventTagMap,
                                               binaryMsgBuf, sizeof(binaryMsgBuf));
    } else {
        err = android_log_processLogBuffer(buf, &entry);
    }
    if (err < 0) {
        goto error;
    }

    if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
        bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);

        if (bytesWritten < 0) {
            perror("output error");
            exit(-1);
        }
    }

    g_outByteCount += bytesWritten;

    if (g_logRotateSizeKBytes > 0
        && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
    ) {
        rotateLogs();
    }

error:
    //fprintf (stderr, "Error processing record\n");
    return;
}

常規日誌的內存佈局是 struct logger_entry | priority | tag | msg,android_log_processLogBuffer 就是把這個「線格式」拆開,填進更易用的 AndroidLogEntry:

typedef struct AndroidLogEntry_t {
    time_t tv_sec;
    long tv_nsec;
    android_LogPriority priority;
    pid_t pid;
    pthread_t tid;
    const char * tag;
    size_t messageLen;
    const char * message;
} AndroidLogEntry;
int android_log_processLogBuffer(struct logger_entry *buf,
                                 AndroidLogEntry *entry)
{
    size_t tag_len;

    entry->tv_sec = buf->sec;
    entry->tv_nsec = buf->nsec;
    entry->priority = buf->msg[0];
    entry->pid = buf->pid;
    entry->tid = buf->tid;
    entry->tag = buf->msg + 1;
    tag_len = strlen(entry->tag);
    entry->messageLen = buf->len - tag_len - 3;
    entry->message = entry->tag + tag_len + 1;

    return 0;
}

而 events / radio 這類二進制日誌則走 android_log_processBinaryLogBuffer,它需要借助 eventTagMap 把 tag 號翻譯成字符串,因為二進制數據沒有固定長度,所以必須由調用方提供一塊可變長的消息緩衝區。

日誌過濾規則

要不要打印某條日誌,由 AndroidLogFormat 描述的過濾規則決定:

struct AndroidLogFormat_t {
    android_LogPriority global_pri;
    FilterInfo *filters;
    AndroidLogPrintFormat format;
};

typedef struct FilterInfo_t {
    char *mTag;
    android_LogPriority mPri;
    struct FilterInfo_t *p_next;
} FilterInfo;

這個對象在 main 裡通過 g_logformat = android_log_format_new() 創建,並根據命令行參數(-s、-v、tag:priority 形式的過濾表達式等)填充。判斷邏輯很簡單:

int android_log_shouldPrintLine (
        AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
{
    return pri >= filterPriForTag(p_format, tag);
}

static android_LogPriority filterPriForTag(
        AndroidLogFormat *p_format, const char *tag)
{
    FilterInfo *p_curFilter;

    for (p_curFilter = p_format->filters
         ; p_curFilter != NULL
         ; p_curFilter = p_curFilter->p_next
         ) {
        if (0 == strcmp(tag, p_curFilter->mTag)) {
            if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
                return p_format->global_pri;
            } else {
                return p_curFilter->mPri;
            }
        }
    }

    return p_format->global_pri;
}

逐級比對 tag,命中且優先級不是 DEFAULT 就用該條目的阈值;否則退回全局阈值。只有日誌自身優先級不低於阈值時才會被輸出。

最終寫出由 android_log_printLogLine 完成,它先按指定格式把 entry 渲染成字符串,再 write 到目標 fd,並處理了短寫與 EINTR:

int android_log_printLogLine(
    AndroidLogFormat *p_format,
    int fd,
    const AndroidLogEntry *entry)
{
    int ret;
    char defaultBuffer[512];
    char *outBuffer = NULL;
    size_t totalLen;

    outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
            sizeof(defaultBuffer), entry, &totalLen);

    if (!outBuffer)
        return -1;

    do {
        ret = write(fd, outBuffer, totalLen);
    } while (ret < 0 && errno == EINTR);

    if (ret < 0) {
        fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
        ret = 0;
        goto done;
    }

    if (((size_t)ret) < totalLen) {
        fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
                (int)totalLen);
        goto done;
    }

done:
    if (outBuffer != defaultBuffer) {
        free(outBuffer);
    }

    return ret;
}

小細節:優先使用 512 字節的棧上緩衝區,不夠再動態分配,最後記得區分是否為棧內存來決定要不要 free。

日誌輪轉

當輸出目標是文件且設置了 -r 大小閾值時,寫滿就會觸發輪轉,把歷史文件依次改名讓位:

static void rotateLogs()
{
    int err;

    // Can't rotate logs if we're not outputting to a file
    if (g_outputFileName == NULL) {
        return;
    }

    close(g_outFD);

    for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
        char *file0, *file1;

        asprintf(&file1, "%s.%d", g_outputFileName, i);

        if (i - 1 == 0) {
            asprintf(&file0, "%s", g_outputFileName);
        } else {
            asprintf(&file0, "%s.%d", g_outputFileName, i - 1);
        }

        err = rename (file0, file1);

        if (err < 0 && errno != ENOENT) {
            perror("while rotating log files");
        }

        free(file1);
        free(file0);
    }

    g_outFD = openLogFile (g_outputFileName);

    if (g_outFD < 0) {
        perror ("couldn't open output file");
        exit(-1);
    }

    g_outByteCount = 0;
}

主線回顧

把整條鏈路串起來就是:main 解析參數 → 建立 log_device_t 鏈表並打開設備 → readLogLines 用 select 複用多設備、read 逐條取出並按時間戳插入隊列 → chooseFirst 挑出最舊的記錄 → processBuffer 解析格式、按 tag/優先級過濾、渲染後寫入 fd → 達到大小閾值則輪轉文件。理解了這個骨架,再去讀 filters、格式(brief / process / tag / thread / raw / time / long)等分支實現就會輕鬆很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved