首页
/ PlatformIO设备监控日志过滤器的自定义实现

PlatformIO设备监控日志过滤器的自定义实现

2025-05-28 08:59:42作者:申梦珏Efrain

在嵌入式开发过程中,串口通信日志记录是一个常见且重要的需求。PlatformIO作为一款强大的嵌入式开发平台,提供了灵活的日志记录机制,允许开发者通过自定义过滤器来实现特定的日志记录功能。

日志记录需求分析

在实际开发中,开发者经常需要将串口通信数据记录到文件中以便后续分析。标准的PlatformIO日志记录功能虽然实用,但有时无法满足特定需求,例如:

  1. 固定日志文件名而非每次生成新文件
  2. 同时记录发送和接收的数据
  3. 为每条消息添加精确时间戳
  4. 控制日志文件的存储位置和命名规则

自定义日志过滤器实现

通过继承PlatformIO提供的DeviceMonitorFilterBase基类,我们可以创建满足上述需求的日志记录器。下面是一个功能完善的实现示例:

import io
import os
from datetime import datetime
from platformio.public import DeviceMonitorFilterBase

class CustomSerialLogger(DeviceMonitorFilterBase):
    NAME = "custom_serial_logger"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._bufferOut = ""
        self._bufferIn = ""
        # 支持不同换行符配置
        if self.options.get("eol") == "CR":
            self._eol = "\r"
        elif self.options.get("eol") == "LF":
            self._eol = "\n"
        else:
            self._eol = "\r\n"
        
    def __del__(self):
        if hasattr(self, '_log_fp') and self._log_fp:
            self._log_fp.close()

    def rx(self, text):
        """处理接收数据"""
        self._bufferIn += text
        if self._bufferIn.endswith(self._eol):
            timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
            log_text = f"接收于 {timestamp} -- {self._bufferIn}"
            self._bufferIn = ""
            self._log_fp.write(log_text)
            self._log_fp.flush()
            return log_text
        return ""

    def tx(self, text):
        """处理发送数据"""
        self._bufferOut += text
        if self._bufferOut.endswith(self._eol):
            timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
            log_text = f"发送于 {timestamp} -- {self._bufferOut}"
            text = self._bufferOut
            print(log_text)  # 同时在控制台显示
            self._bufferOut = ""
            self._log_fp.write(log_text)
            self._log_fp.flush()
            return text
        return ""

    def __call__(self):
        """初始化日志文件"""
        if not os.path.isdir("logs"):
            os.makedirs("logs")
        log_file_path = os.path.join("logs", "serial-monitor.log")
        print(f"--- 日志将保存至 {os.path.abspath(log_file_path)} ---")
        self._log_fp = io.open(log_file_path, "w", encoding="utf-8")
        self._log_fp.write(f"--- 日志日期: {datetime.now().strftime('20%y.%m.%d -- %H:%M')} ---\r\n")
        self._log_fp.flush()
        return self

功能特点解析

  1. 固定文件名:始终使用"serial-monitor.log"作为日志文件名,覆盖写入而非追加
  2. 完整通信记录:同时记录发送(tx)和接收(rx)的数据
  3. 精确时间戳:每条消息都带有毫秒级精度的时间戳
  4. 自动目录创建:自动创建logs目录存放日志文件
  5. 换行符支持:可配置CR、LF或CRLF作为行结束符
  6. 实时写入:每条消息立即写入文件,避免数据丢失

配置使用方法

在项目的platformio.ini配置文件中添加以下内容即可启用自定义日志过滤器:

monitor_filters = custom_serial_logger

实际应用建议

  1. 日志文件管理:对于长期项目,建议扩展功能实现日志轮转或按日期分割
  2. 性能考量:高频通信场景下,可考虑缓冲多条消息后批量写入
  3. 异常处理:增加文件写入失败的异常处理逻辑
  4. 格式扩展:支持JSON等结构化日志格式便于后续分析

通过这种自定义日志记录方案,开发者可以获得更加符合项目需求的通信日志,大大提升调试和分析效率。PlatformIO的这种可扩展设计充分体现了其作为专业嵌入式开发平台的灵活性。

登录后查看全文
热门项目推荐
相关项目推荐