乐鑫技术交流
直播中

北冥有熊

8年用户 870经验值
擅长:131594
私信 关注
[问答]

有没有把esp日志保存到flash的方法?

目前使用vscode+esp-idf开发,版本v4.4.2,请问各位大佬有没有把esp日志保存到flash的方法?日志如果只通过串口输出,对于物联网设备当出现问题的时候比较难定位问题,主要就是看不到日志,出现问题需要连接电脑后复现问题再通过日志定位问题,有些问题偶现的,复现的概率比较低,所以希望esp能具备日志保存到flash(ESP_LOGIESP_LOGWESP_LOGE等等),反观对比rt-thread的easyLog模块,是支持日志输出到flash的。
                                                

回帖(1)

青sky

2024-6-13 16:37:20
要在ESP32设备上将日志保存到Flash中,您可以使用以下方法:

1. 创建一个自定义的日志记录器,该记录器将日志写入Flash。

首先,您需要创建一个自定义的日志记录器。这可以通过继承`esp_log`库中的`esp_log_impl_t`结构来实现。然后,实现`log()`函数,将日志写入Flash。

```c
#include "esp_log.h"
#include "esp_flash.h"

typedef struct {
    esp_log_impl_t base;
    size_t flash_offset;
} flash_log_impl_t;

static esp_err_t flash_log_write(flash_log_impl_t *impl, const char *msg, size_t len) {
    esp_err_t ret = esp_flash_write(impl->flash_offset, (const void *)msg, len);
    if (ret == ESP_OK) {
        impl->flash_offset += len;
    }
    return ret;
}

static esp_err_t flash_log_log(esp_log_impl_t *_impl, esp_log_level_t level, const char *tag, const char *format, va_list args) {
    flash_log_impl_t *impl = __containerof(_impl, flash_log_impl_t, base);
    char *buffer = (char *)malloc(ESP_LOG_MAX_MESSAGE_LENGTH);
    if (!buffer) {
        return ESP_ERR_NO_MEM;
    }

    vsnprintf(buffer, ESP_LOG_MAX_MESSAGE_LENGTH, format, args);
    esp_err_t ret = flash_log_write(impl, buffer, strlen(buffer) + 1);
    free(buffer);
    return ret;
}

static void flash_log_deinit(esp_log_impl_t *_impl) {
    // Clean up if needed
}

static esp_log_impl_t flash_log_impl = {
    .log = &flash_log_log,
    .deinit = &flash_log_deinit,
};

static flash_log_impl_t g_flash_log_impl = {
    .base = &flash_log_impl,
    .flash_offset = FLASH_LOG_OFFSET,
};

void flash_log_init(size_t flash_offset) {
    g_flash_log_impl.flash_offset = flash_offset;
    esp_log_set_vprintf(&flash_log_impl.log);
}
```

2. 在应用程序中使用自定义的日志记录器。

在您的应用程序中,调用`flash_log_init()`函数,传入Flash中用于存储日志的偏移量。然后,您可以使用`ESP_LOGx`宏来记录日志,这些日志将被写入Flash。

```c
#include "flash_log.h"

void app_main() {
    flash_log_init(FLASH_LOG_OFFSET);

    ESP_LOGI(TAG, "This log will be saved to Flash");

    // Your application code
}
```

3. 从Flash读取日志。

当您需要从Flash中读取日志时,可以使用`esp_flash_read()`函数。您可以编写一个函数来解析存储在Flash中的日志,并将其输出到串口或其他日志记录器。

请注意,这种方法可能会增加应用程序的复杂性,并可能影响性能。此外,Flash的写入次数有限,因此请确保您的日志记录策略不会过快耗尽Flash的寿命。
举报

更多回帖

发帖
×
20
完善资料,
赚取积分