[log] Add ESPHOME_DEBUG_ASSERT for log function invariants

Add ESPHOME_DEBUG_ASSERT macro that only fires when ESPHOME_DEBUG is
defined. Use it to assert global_logger is not null in log functions.
Enable ESPHOME_DEBUG in C++ unit test builds so these assertions are
active during testing but have zero cost in production firmware.
This commit is contained in:
J. Nick Koston
2026-03-05 22:05:17 -10:00
parent d8600b5bc9
commit 6e36af6c4b
3 changed files with 13 additions and 0 deletions
+4
View File
@@ -17,6 +17,7 @@ namespace esphome {
// tests/component_tests/logger/test_logger.py.
void HOT esp_log_printf_(int level, const char *tag, int line, const char *format, ...) { // NOLINT
#ifdef USE_LOGGER
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
va_list arg;
va_start(arg, format);
logger::global_logger->log_vprintf_(static_cast<uint8_t>(level), tag, line, format, arg);
@@ -27,6 +28,7 @@ void HOT esp_log_printf_(int level, const char *tag, int line, const char *forma
#ifdef USE_STORE_LOG_STR_IN_FLASH
void HOT esp_log_printf_(int level, const char *tag, int line, const __FlashStringHelper *format, ...) {
#ifdef USE_LOGGER
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
va_list arg;
va_start(arg, format);
logger::global_logger->log_vprintf_(static_cast<uint8_t>(level), tag, line, format, arg);
@@ -37,6 +39,7 @@ void HOT esp_log_printf_(int level, const char *tag, int line, const __FlashStri
void HOT esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args) { // NOLINT
#ifdef USE_LOGGER
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
logger::global_logger->log_vprintf_(static_cast<uint8_t>(level), tag, line, format, args);
#endif
}
@@ -44,6 +47,7 @@ void HOT esp_log_vprintf_(int level, const char *tag, int line, const char *form
#ifdef USE_ESP32
int HOT esp_idf_log_vprintf_(const char *format, va_list args) { // NOLINT
#ifdef USE_LOGGER
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
logger::global_logger->log_vprintf_(ESPHOME_LOG_LEVEL, "esp-idf", 0, format, args);
#endif
return 0;
+8
View File
@@ -4,6 +4,14 @@
#include <cassert>
#include <cstdarg>
// Debug assert that only fires when ESPHOME_DEBUG is defined (e.g. in CI/test builds).
// Zero cost in production firmware.
#ifdef ESPHOME_DEBUG
#define ESPHOME_DEBUG_ASSERT(expr) assert(expr) // NOLINT
#else
#define ESPHOME_DEBUG_ASSERT(expr) ((void) 0)
#endif
// for PRIu32 and friends
#include <cinttypes>
#include <string>
+1
View File
@@ -100,6 +100,7 @@ def create_test_config(config_name: str, includes: list[str]) -> dict:
"build_flags": [
"-Og", # optimize for debug
"-DUSE_TIME_TIMEZONE", # enable timezone code paths for testing
"-DESPHOME_DEBUG", # enable debug assertions
],
"debug_build_flags": [ # only for debug builds
"-g3", # max debug info