ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
logger.cpp
Go to the documentation of this file.
1#include "logger.h"
2#include <cinttypes>
3#include <cstring>
4
6#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
9
10#if defined(USE_ESP32) && defined(USE_NETWORK)
11#include <sdkconfig.h>
12#if defined(CONFIG_LWIP_TCPIP_CORE_LOCKING) && defined(USE_ESPHOME_TASK_LOG_BUFFER)
13#include "lwip/sys.h"
14#define USE_LOGGER_DEFER_UNDER_LWIP_LOCK
15#endif
16#endif
17
18namespace esphome::logger {
19
20ESPHOME_LOG_TAG(TAG, "logger");
21
22#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
23// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
24// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
25//
26// For non-main threads/tasks:
27// - WITH task log buffer: Prefer sending to ring buffer for async processing
28// - Avoids allocating stack memory for console output in normal operation
29// - Prevents console corruption from concurrent writes by multiple threads
30// - Messages are serialized through main loop for proper console output
31// - Fallback to emergency console logging only if ring buffer is full
32// - WITHOUT task log buffer: Only emergency console output, no callbacks
33//
34// Optimized for the common case: 99.9% of logs come from the main thread
35void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args) { // NOLINT
36 if (level > this->level_for(tag))
37 return;
38
39#if defined(USE_ESP32) || defined(USE_LIBRETINY)
40 // Get task handle once - used for both main task check and passing to non-main thread handler
41 TaskHandle_t current_task = xTaskGetCurrentTaskHandle();
42 const bool is_main_task = (current_task == this->main_task_);
43#elif (USE_ZEPHYR)
44 k_tid_t current_task = k_current_get();
45 const bool is_main_task = (current_task == this->main_task_);
46#else // USE_HOST
47 const bool is_main_task = pthread_equal(pthread_self(), this->main_thread_);
48#endif
49
50 // Fast path: main thread, no recursion (99.9% of all logs)
51 // Pass nullptr for thread_name since we already know this is the main task
52 if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
53#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
54 // lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
55 // to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
56 // can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
57 if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
58 [[unlikely]] {
59 this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
60 return;
61 }
62#endif
63 this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
64 return;
65 }
66
67 // Main task with recursion - silently drop to prevent infinite loop
68 if (is_main_task) {
69 return;
70 }
71
72 // Non-main thread handling (~0.1% of logs)
73 // Resolve thread name once and pass it through the logging chain.
74 // ESP32/LibreTiny: use TaskHandle_t overload to avoid redundant xTaskGetCurrentTaskHandle()
75 // (we already have the handle from the main task check above).
76 // Host: pass a stack buffer for pthread_getname_np to write into.
77#if defined(USE_ESP32) || defined(USE_LIBRETINY)
78 const char *thread_name = get_thread_name_(current_task);
79#elif defined(USE_ZEPHYR)
80 char thread_name_buf[MAX_POINTER_REPRESENTATION];
81 const char *thread_name = get_thread_name_(thread_name_buf, current_task);
82#else // USE_HOST
83 char thread_name_buf[THREAD_NAME_BUF_SIZE];
84 const char *thread_name = this->get_thread_name_(thread_name_buf);
85#endif
86 this->log_vprintf_non_main_thread_(level, tag, line, format, args, thread_name);
87}
88
89// Handles non-main thread logging only
90// Kept separate from hot path to improve instruction cache performance
91void Logger::log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
92 const char *thread_name) {
93 // Check if already in recursion for this non-main thread/task
94 if (this->is_non_main_task_recursive_()) {
95 return;
96 }
97
98 // RAII guard - automatically resets on any return path
99 auto guard = this->make_non_main_task_guard_();
100
101 bool message_sent = false;
102#ifdef USE_ESPHOME_TASK_LOG_BUFFER
103 // For non-main threads/tasks, queue the message for callbacks
104 message_sent =
105 this->log_buffer_.send_message_thread_safe(level, tag, static_cast<uint16_t>(line), thread_name, format, args);
106 if (message_sent) {
107 // Enable logger loop to process the buffered message
108 // This is safe to call from any context including ISRs
110 }
111#endif
112 // Emergency console logging for non-main threads when ring buffer is full or disabled
113 // This is a fallback mechanism to ensure critical log messages are visible
114 // Note: This may cause interleaved/corrupted console output if multiple threads
115 // log simultaneously, but it's better than losing important messages entirely
116#ifdef USE_HOST
117 if (!message_sent)
118#else
119 if (!message_sent && this->baud_rate_ > 0) // If logging is enabled, write to console
120#endif
121 {
122#ifdef USE_HOST
123 // Host always has console output - no baud_rate check needed
124 static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 512;
125#else
126 // Maximum size for console log messages (includes null terminator)
127 static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 144;
128#endif
129 char console_buffer[MAX_CONSOLE_LOG_MSG_SIZE]; // MUST be stack allocated for thread safety
130 LogBuffer buf{console_buffer, MAX_CONSOLE_LOG_MSG_SIZE};
131 this->format_log_to_buffer_with_terminator_(level, tag, line, format, args, buf, thread_name);
132 this->write_to_console_(buf);
133 }
134
135 // RAII guard automatically resets on return
136}
137#else
138// Implementation for single-task platforms (ESP8266, RP2040)
139// Logging calls are NOT thread-safe: global_recursion_guard_ is a plain bool and tx_buffer_ has no locking.
140// Not a problem in practice yet since Zephyr has no API support (logs are console-only).
141void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args) { // NOLINT
142 if (level > this->level_for(tag) || global_recursion_guard_)
143 return;
144 // Other single-task platforms don't have thread names, so pass nullptr
145 this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
146}
147#endif // USE_ESP32 || USE_HOST || USE_LIBRETINY || USE_ZEPHYR
148
149#ifdef USE_ESP8266
150// ESP8266 keeps log format strings in flash.
151//
152// This function handles format strings stored in flash memory (PROGMEM) to save RAM.
153// Uses vsnprintf_P to read the format string directly from flash without copying to RAM.
154//
155void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format,
156 va_list args) { // NOLINT
157 if (level > this->level_for(tag) || global_recursion_guard_)
158 return;
159
160 this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
161}
162#endif // USE_ESP8266
163
164#if defined(USE_LOGGER_RUNTIME_TAG_LEVELS) || defined(USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS)
165// Level for tag from a per-tag map, or fallback when the tag has none; tags may live in flash
166static inline uint8_t tag_level(const std::map<const char *, uint8_t, CStrCompare> &levels, const char *tag,
167 uint8_t fallback) {
168 if (levels.empty())
169 return fallback;
170 auto it = levels.find(FlashTag{tag});
171 return it != levels.end() ? it->second : fallback;
172}
173#endif
174
175uint8_t Logger::get_log_level(const char *tag) { return this->level_for(tag); }
176
177inline uint8_t Logger::level_for(const char *tag) {
178#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
179 return tag_level(this->log_levels_, tag, this->current_level_);
180#else
181 return this->current_level_;
182#endif
183}
184
185#ifdef USE_LOGGER_BOOT_LOG_BUFFER
186inline uint8_t Logger::boot_level_for_(const char *tag) {
187#ifdef USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS
188 return tag_level(this->boot_log_levels_, tag, ESPHOME_LOGGER_BOOT_LOG_LEVEL);
189#else
190 return ESPHOME_LOGGER_BOOT_LOG_LEVEL;
191#endif
192}
193#endif
194
195Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
196#if defined(USE_ESP32) || defined(USE_LIBRETINY)
197 this->main_task_ = xTaskGetCurrentTaskHandle();
198#elif defined(USE_ZEPHYR)
199 this->main_task_ = k_current_get();
200#elif defined(USE_HOST)
201 this->main_thread_ = pthread_self();
202#endif
203}
204
205#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
207 this->process_messages_();
208#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
209 this->cdc_loop_();
210#endif
211}
212#endif
213
215#ifdef USE_ESPHOME_TASK_LOG_BUFFER
216 // Process any buffered messages when available
217 if (this->log_buffer_.has_messages()) {
218 // Prevent main-task logs emitted by listener callbacks (e.g. the API send path) from re-entering
219 // and corrupting the shared tx_buffer_ / API shared_write_buffer_ while we are draining here.
220 // Mirrors the guard held by log_message_to_buffer_and_send_ on the synchronous logging path.
223 uint16_t text_length;
224 while (this->log_buffer_.borrow_message_main_loop(message, text_length)) {
225 const char *thread_name = message->thread_name[0] != '\0' ? message->thread_name : nullptr;
226 LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
227 this->format_buffered_message_and_notify_(message->level, message->tag, message->line, thread_name,
228 message->text_data(), text_length, buf);
229 // Release the message to allow other tasks to use it as soon as possible
232 }
233 }
234#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
235 else {
236 // No messages to process, disable loop if appropriate
237 // This reduces overhead when there's no async logging activity
239 }
240#endif
241#endif // USE_ESPHOME_TASK_LOG_BUFFER
242}
243
244#ifdef USE_LOGGER_BOOT_LOG_BUFFER
245// Each boot_log_buffer_ record is this header followed by len bytes of text
246struct __attribute__((packed)) BootLogRecord {
247 uint16_t len;
248 uint8_t level;
249 uint32_t ms;
250 const char *tag; // tags are string literals, so the pointer stays valid
251};
252// Stored text is capped so the replay header, the reset and the null terminator always fit in the transmit buffer
253static constexpr uint16_t BOOT_LOG_MAX_TEXT =
254 ESPHOME_LOGGER_TX_BUFFER_SIZE - LogBuffer::REPLAY_HEADER_MAX_SIZE - LogBuffer::ANSI_RESET_LEN - 1;
255
256void Logger::boot_log_capture_(uint8_t level, const char *tag, const LogBuffer &buf) {
257 // The most verbose level any tag keeps; cheaper than the per-tag lookup for the lines that cannot qualify
258 if (level > ESPHOME_LOGGER_BOOT_LOG_MAX_LEVEL || level == ESPHOME_LOG_LEVEL_NONE ||
259 level > this->boot_level_for_(tag))
260 return;
261 // Strip the color write_header put in front and the reset at the end; the replay adds its own around the stamp
262 const char *text = buf.data;
263 uint16_t len = buf.pos;
264 if (len >= LogBuffer::ANSI_COLOR_LEN && text[0] == '\033') {
267 }
269 memcmp(text + len - LogBuffer::ANSI_RESET_LEN, "\033[0m", LogBuffer::ANSI_RESET_LEN) == 0)
271 if (len > BOOT_LOG_MAX_TEXT)
272 len = BOOT_LOG_MAX_TEXT;
273 if (this->boot_log_pos_ + sizeof(BootLogRecord) + len > ESPHOME_LOGGER_BOOT_LOG_BUFFER_SIZE) {
274 this->boot_log_dropped_++;
275 return;
276 }
277 const BootLogRecord record{len, level, millis(), tag};
278 char *p = this->boot_log_buffer_ + this->boot_log_pos_;
279 memcpy(p, &record, sizeof(record));
280 memcpy(p + sizeof(record), text, len);
281 this->boot_log_pos_ += sizeof(record) + len;
282}
283
285 // The replay shares tx_buffer_ with normal logging, so it is dropped like any other re-entrant log
286 bool &recursion_guard = this->main_loop_recursion_guard_();
287 if (recursion_guard)
288 return;
289 this->boot_log_done_ = true; // Stops capture first, so the replay output is not buffered again
290 // Dropped lines are reported at WARN so a device at level WARN still learns the buffer was too small
291 esp_log_printf_(this->boot_log_dropped_ > 0 ? ESPHOME_LOG_LEVEL_WARN : ESPHOME_LOG_LEVEL_INFO, TAG, __LINE__,
292 ESPHOME_LOG_FORMAT("Replaying boot logs (%u bytes used, %u lines dropped)"), this->boot_log_pos_,
293 this->boot_log_dropped_);
294 RecursionGuard guard(recursion_guard);
295 uint16_t pos = 0;
296 while (pos + sizeof(BootLogRecord) <= this->boot_log_pos_) {
297 BootLogRecord record;
298 memcpy(&record, this->boot_log_buffer_ + pos, sizeof(record));
299 const char *text = this->boot_log_buffer_ + pos + sizeof(record);
300 pos += sizeof(record) + record.len;
301 if (record.level > this->level_for(record.tag))
302 continue;
303 // The stored text already carries its [LEVEL][tag:line] header
304 LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
305 buf.write_replay_header(record.level, record.ms);
306 buf.write_body(text, record.len);
307 this->notify_listeners_(record.level, record.tag, buf);
309 }
310}
311#else
312void Logger::replay_boot_logs() { ESP_LOGW(TAG, "Boot log buffer not configured (set 'boot_log_buffer_size')"); }
313#endif // USE_LOGGER_BOOT_LOG_BUFFER
314#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
315void Logger::set_log_level(const char *tag, uint8_t log_level) { this->log_levels_[tag] = log_level; }
316#endif
317#ifdef USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS
318void Logger::set_boot_log_level(const char *tag, uint8_t log_level) { this->boot_log_levels_[tag] = log_level; }
319#endif
320
321// Log level strings - packed into flash on ESP8266, indexed by log level (0-7)
322PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE");
323
324static const LogString *get_log_level_str(uint8_t level) {
325 return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
326}
327
329 ESP_LOGCONFIG(TAG,
330 "Logger:\n"
331 " Max Level: %s\n"
332 " Initial Level: %s",
333 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)),
334 LOG_STR_ARG(get_log_level_str(this->current_level_)));
335#ifndef USE_HOST
336 ESP_LOGCONFIG(TAG,
337 " Log Baud Rate: %" PRIu32 "\n"
338 " Hardware UART: %s",
339 this->baud_rate_, LOG_STR_ARG(get_uart_selection_()));
340#endif
341#ifdef USE_ESPHOME_TASK_LOG_BUFFER
342#ifdef USE_HOST
343 ESP_LOGCONFIG(TAG, " Task Log Buffer Slots: %u", static_cast<unsigned int>(this->log_buffer_.size()));
344#else
345 ESP_LOGCONFIG(TAG, " Task Log Buffer Size: %u bytes", static_cast<unsigned int>(this->log_buffer_.size()));
346#endif
347#endif
348#ifdef USE_LOGGER_BOOT_LOG_BUFFER
349 ESP_LOGCONFIG(TAG, " Boot Log Buffer Size: %u bytes", ESPHOME_LOGGER_BOOT_LOG_BUFFER_SIZE);
350#endif
351
352#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
353 for (auto &it : this->log_levels_) {
354 ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.first, LOG_STR_ARG(get_log_level_str(it.second)));
355 }
356#endif
357#ifdef USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS
358 for (auto &it : this->boot_log_levels_) {
359 ESP_LOGCONFIG(TAG, " Boot Level for '%s': %s", it.first, LOG_STR_ARG(get_log_level_str(it.second)));
360 }
361#endif
362#ifdef USE_ZEPHYR
363 dump_crash_();
364#ifdef USE_BOOTLOADER_ADAFRUIT
365 this->dump_bootloader_();
366#endif
367 if (!device_is_ready(this->uart_dev_)) {
368 ESP_LOGE(TAG, " %s is not ready.", LOG_STR_ARG(get_uart_selection_()));
369 }
370#endif
371 // Warn users that VERBOSE/VERY_VERBOSE logging impacts performance.
372 // Only the compiled log level matters — all log calls up to this level
373 // are in the binary and will be formatted (vsnprintf) and block UART.
374#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
375 ESP_LOGW(TAG, "VERY_VERBOSE logging is active — significant performance impact, short-term debugging only\n"
376 " May cause connection instability. Set log level to DEBUG or lower for long-term use.");
377#elif ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
378 ESP_LOGI(TAG, "VERBOSE logging is active — performance impact, short-term debugging only\n"
379 " Set log level to DEBUG or lower for long-term use.");
380#endif
381}
382
383void Logger::set_log_level(uint8_t level) {
384 if (level > ESPHOME_LOG_LEVEL) {
385 level = ESPHOME_LOG_LEVEL;
386 ESP_LOGW(TAG, "Cannot set log level higher than pre-compiled %s",
387 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)));
388 }
389 this->current_level_ = level;
390#ifdef USE_LOGGER_LEVEL_LISTENERS
391 for (auto *listener : this->level_listeners_)
392 listener->on_log_level_change(level);
393#endif
394}
395
396Logger *global_logger = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
397
398} // namespace esphome::logger
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
Logger component for all ESPHome logging.
Definition logger.h:149
void HOT notify_listeners_(uint8_t level, const char *tag, const LogBuffer &buf)
Definition logger.h:275
char boot_log_buffer_[ESPHOME_LOGGER_BOOT_LOG_BUFFER_SIZE]
Definition logger.h:419
const char *HOT get_thread_name_()
Definition logger.h:439
void dump_config() override
Definition logger.cpp:328
bool HOT is_non_main_task_recursive_() const
Definition logger.h:493
NonMainTaskRecursionGuard make_non_main_task_guard_()
Definition logger.h:496
const LogString * get_uart_selection_()
uint8_t level_for(const char *tag)
Definition logger.cpp:177
void loop() override
Definition logger.cpp:206
uint8_t get_log_level()
Definition logger.h:187
void log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args)
Definition logger.cpp:35
void HOT log_message_to_buffer_and_send_(bool &recursion_guard, uint8_t level, const char *tag, int line, FormatType format, va_list args, const char *thread_name)
Definition logger.h:298
void replay_boot_logs()
Send the lines captured during boot to the listeners and stop capturing; safe to call repeatedly.
Definition logger.cpp:284
char tx_buffer_[ESPHOME_LOGGER_TX_BUFFER_SIZE+1]
Definition logger.h:414
void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line, const char *thread_name, const char *text, uint16_t text_length, LogBuffer &buf)
Definition logger.h:321
std::map< const char *, uint8_t, CStrCompare > log_levels_
Definition logger.h:379
pthread_t main_thread_
Definition logger.h:360
std::vector< LoggerLevelListener * > level_listeners_
Definition logger.h:386
void disable_loop_when_buffer_empty_()
Definition logger.h:519
void HOT format_log_to_buffer_with_terminator_(uint8_t level, const char *tag, int line, const char *format, va_list args, LogBuffer &buf, const char *thread_name)
Definition logger.h:257
void HOT write_log_buffer_to_console_(LogBuffer &buf)
Definition logger.h:289
uint8_t boot_level_for_(const char *tag)
Definition logger.cpp:186
void set_log_level(uint8_t level)
Set the default log level for this logger.
Definition logger.cpp:383
void boot_log_capture_(uint8_t level, const char *tag, const LogBuffer &buf)
Copy a formatted line at or above the boot log level (outer ANSI codes stripped) into the boot log bu...
Definition logger.cpp:256
bool & main_loop_recursion_guard_()
Definition logger.h:407
void set_boot_log_level(const char *tag, uint8_t log_level)
Set the boot log level of the specified tag.
Definition logger.cpp:318
void HOT write_to_console_(LogBuffer &buf)
Definition logger.h:283
void log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args, const char *thread_name)
Definition logger.cpp:91
logger::TaskLogBuffer log_buffer_
Definition logger.h:416
uint16_t boot_log_dropped_
Definition logger.h:391
bool main_task_recursion_guard_
Definition logger.h:402
const device * uart_dev_
Definition logger.h:354
std::map< const char *, uint8_t, CStrCompare > boot_log_levels_
Definition logger.h:376
Logger(uint32_t baud_rate)
Definition logger.cpp:195
bool borrow_message_main_loop(LogMessage *&message, uint16_t &text_length)
bool send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, const char *thread_name, const char *format, va_list args)
const LogString * message
Definition component.cpp:35
const char * format
Logger * global_logger
Definition logger.cpp:396
PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE")
ESPHOME_LOG_TAG(TAG, "logger")
void HOT esp_log_printf_(int level, const char *tag, int line, const char *format,...)
Definition log.cpp:21
const void size_t len
Definition hal.h:68
size_t size_t pos
Definition helpers.h:1333
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
void write_replay_header(uint8_t level, uint32_t ms)
Definition log_buffer.h:122
static constexpr uint16_t ANSI_COLOR_LEN
Definition log_buffer.h:117
static constexpr uint16_t ANSI_RESET_LEN
Definition log_buffer.h:118
static constexpr uint16_t REPLAY_HEADER_MAX_SIZE
Definition log_buffer.h:120