Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

使用Android Logger 可以用c++语言从logd中读取日志吗

  1. User

    使用Android Logger 可以用c++语言从logd中读取日志吗

  2. Assistant

    是的,可以使用c++语言从logd中读取日志。

    以下是实现方法:

    1. 在c++文件中引入以下头文件:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <android/log.h>
    
    1. 使用logcat命令导出log日志

    可以使用以下命令将logcat日志输出到文件中:

    adb logcat > logfile.txt
    
    1. 使用fopen和fgets读取日志文件内容

    可以使用以下代码从输出的日志文件中读取内容:

    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    
    fp = fopen("logfile.txt", "r");
    if (fp == NULL) {
        printf("Failed to open log file");
        exit(EXIT_FAILURE);
    }
    
    while ((read = getline(&line, &len, fp)) != -1) {
        printf("%s", line);
    }
    
    fclose(fp);
    if (line)
        free(line);
    

    以上代码将逐行读取日志文件,并在控制台上打印出来。

    注意:在实现时,需要将printf改为Android日志输出函数__android_log_print。如下:

    #include <android/log.h>
    
    #define LOG_TAG "MY_LOG"
    #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
    
    int main() {
        FILE * fp;
        char * line = NULL;
        size_t len = 0;
        ssize_t read;
    
        fp = fopen("logfile.txt", "r");
        if (fp == NULL) {
            LOGI("Failed to open log file");
            exit(EXIT_FAILURE);
        }
    
        while ((read = getline(&line, &len, fp)) != -1) {
            LOGI("%s", line);
        }
    
        fclose(fp);
        if (line)
            free(line);
        
        return 0;
    }
    
  3. User

    对第一种实现方法能给出实现代码吗

  4. Assistant

    下面是一个简单的使用Android Logger从logcat中读取日志的c++代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <android/log.h>
    
    #define LOG_TAG "MY_LOG"
    
    int main() {
        android_LogPriority priority;
        const char* tag;
        const char* message;
        while (1) {
            if (__android_log_buffer_read(LOG_ID_MAIN, (log_time*)nullptr, &priority, &tag, &message) > 0) {
                __android_log_print(priority, LOG_TAG, "%s", message);
            }
        }
        return 0;
    }
    

    其中LOG_ID_MAIN是指主log缓冲区,可以根据需要更改为空闲日志缓冲区或其他缓冲区。

    该程序将不断从logcat缓冲区读取日志,并将其输出到控制台。可以在Android设备上以root权限运行此程序,以便从logcat中读取日志。

    注意:在运行时需要给予程序访问log权限,可以使用以下命令:

    adb shell su -c "chmod 777 /dev/log/*"
    

    这样就可以通过c++代码读取logcat中的日志了。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.