This document explains how to use the modular logging system (logger.h / logger.c) designed for STM32 MCU projects with UART and SD card output.
Features
- UART output with blocking, interrupt (IT), or DMA modes
- Optional SD card logging (FatFS required)
- Ring buffer for non-blocking UART output
- Runtime log level filtering (ERROR, WARN, INFO, DEBUG)
- Logging disable and flush support
- Easy to override hooks for custom output targets
Files
- logger.h – Public interface and configuration
- logger.c – Implementation with ring buffer, UART/SD output, and FatFS integration
Configuration
Set these macros before including logger.h or define them in a logger_config.h (optional).
#define LOG_USE_UART 1
#define LOG_USE_SD 1
#define LOG_USE_IT 1
#define LOG_USE_DMA 0
#define LOG_BUFFER_SIZE 256
#define LOG_RING_BUFFER_SIZE 1024
Only one of LOG_USE_DMA or LOG_USE_IT should be enabled.
Initialization and Usage
Initialization:
Modular and flexible logging system for STM32-based MCU projects.
void Log_Init(void)
Initialize the logging system.
Definition logger.c:113
void Log_SetLevel(LogLevel level)
Set the active logging level.
Definition logger.c:128
@ LOG_LEVEL_DEBUG
Definition logger.h:53
Logging:
void Log(LogLevel level, const char *format,...)
Log a formatted message if the level passes the threshold.
Definition logger.c:149
@ LOG_LEVEL_INFO
Definition logger.h:52
Disabling/Flushing:
void Log_Disable(void)
Disable all logging at runtime.
Definition logger.c:135
void Log_Flush(void)
Flush output buffers.
Definition logger.c:169
UART Integration
You must define a UART handle externally:
extern UART_HandleTypeDef huart1;
And call the UART complete callback:
Logger_HAL_UART_TxCpltCallback(huart);
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
UART transmission complete callback handler. Should be called from HAL_UART_TxCpltCallback().
Definition logger.c:95
SD Card Integration
Requires:
- FatFS (ff.h) and disk I/O working
- Mount must be done before Log_Init()
- Writes to log.txt in append mode
Auto flushes on Log_Flush() using f_sync():
f_open(&log_file, "log.txt", FA_OPEN_ALWAYS | FA_WRITE);
f_lseek(&log_file, f_size(&log_file));
f_write(&log_file, msg, strlen(msg), &bw);
f_sync(&log_file);
Custom Output Hooks
You can override either of these functions to customize output:
__attribute__((weak)) void Log_Write_UART(const char *msg)
UART output hook. Can be overridden by user.
Definition logger.c:196
For example, redirect output to USB or a BLE service.
Example Session
@ LOG_LEVEL_ERROR
Definition logger.h:50
Tips
- You can queue logs during runtime with LOG_USE_IT or LOG_USE_DMA
- For CLI coexistence, use a shared ring buffer or alternate UARTs
- For safety, call Log_Flush() before shutting down or resetting the MCU