Skip to content

CircularLogPrinter - In-Memory Logging with Optional Output

Path: src/modbus/circular_log_printer.h

Revision History:

  • 2023-11-15: Initial documentation

CircularLogPrinter is an Arduino-compatible Print implementation that stores the last N log lines in a circular buffer. It can optionally mirror all output to another stream (like Serial). The component is designed to be 100% reinterpret-cast-free for MISRA/CPPCHECK compliance, making it suitable for industrial applications.

  • FreeRTOS (for optional thread safety)
  • ESP32 IDF framework
  • Global Serial object (when using default constructor)
  • using LogRingBuffer = char[LOG_BUFFER_LINES][LOG_BUFFER_LINE_LENGTH]
  • class CircularLogPrinter: A Print implementation storing log lines in a circular buffer
  • Configurable circular buffer size via macros
  • Thread-safe operation (optional)
  • Ability to attach to ESP-IDF’s logging system
  • No pointer type casting (MISRA compliant)
  • Retrieves log history by line number
  • Optional mirroring to any Print-compatible output
  • Efficient multi-byte writes

CircularLogPrinter

Arduino

Print

ESP_Log

write(byte)

write non-newline

write newline

Store line & update indices

clear()

write(byte)

Ready

Accumulating

CommittingLine

Cleared

  • Consider using a more efficient buffer strategy for high-volume logging
  • Potential optimization by pre-allocating buffer space when attaching to ESP-IDF log
  • No direct security concerns as this is an output-only component
  • Consider adding sanitization for control characters that could affect terminal displays
  • Already designed for MISRA/CPPCHECK compliance with no reinterpret casts
  • Consider adding formal verification of buffer access bounds
  • Adjust LOG_BUFFER_LINES and LOG_BUFFER_LINE_LENGTH based on available memory and application needs
  • For performance-critical applications, consider disabling thread safety with LOG_BUFFER_THREAD_SAFE=0
  • When using with Modbus, attach to ESP-IDF logging to capture all system messages including Modbus communication logs
#include "circular_log_printer.h"
// Create logger with default output (Serial)
CircularLogPrinter logger;
void setup() {
Serial.begin(115200);
// Attach to ESP-IDF logging system
logger.attachToEspLog();
// Log some messages
logger.println("System initializing...");
// Later, retrieve historical logs
for (size_t i = 0; i < logger.lines(); i++) {
Serial.println(logger.getLine(i));
}
}