ESPHome 2026.10.2
Loading...
Searching...
No Matches
logger.cpp
Go to the documentation of this file.
1#include "logger.h"
2#include <cinttypes>
3
5#include "esphome/core/hal.h"
6#include "esphome/core/log.h"
8
9namespace esphome::logger {
10
11static const char *const TAG = "logger";
12
13#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
14// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
15// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
16//
17// For non-main threads/tasks:
18// - WITH task log buffer: Prefer sending to ring buffer for async processing
19// - Avoids allocating stack memory for console output in normal operation
20// - Prevents console corruption from concurrent writes by multiple threads
21// - Messages are serialized through main loop for proper console output
22// - Fallback to emergency console logging only if ring buffer is full
23// - WITHOUT task log buffer: Only emergency console output, no callbacks
24//
25// Optimized for the common case: 99.9% of logs come from the main thread
26void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args) { // NOLINT
27 if (level > this->level_for(tag))
28 return;
29
30#if defined(USE_ESP32) || defined(USE_LIBRETINY)
31 // Get task handle once - used for both main task check and passing to non-main thread handler
32 TaskHandle_t current_task = xTaskGetCurrentTaskHandle();
33 const bool is_main_task = (current_task == this->main_task_);
34#elif (USE_ZEPHYR)
35 k_tid_t current_task = k_current_get();
36 const bool is_main_task = (current_task == this->main_task_);
37#else // USE_HOST
38 const bool is_main_task = pthread_equal(pthread_self(), this->main_thread_);
39#endif
40
41 // Fast path: main thread, no recursion (99.9% of all logs)
42 // Pass nullptr for thread_name since we already know this is the main task
43 if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
44 this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
45 return;
46 }
47
48 // Main task with recursion - silently drop to prevent infinite loop
49 if (is_main_task) {
50 return;
51 }
52
53 // Non-main thread handling (~0.1% of logs)
54 // Resolve thread name once and pass it through the logging chain.
55 // ESP32/LibreTiny: use TaskHandle_t overload to avoid redundant xTaskGetCurrentTaskHandle()
56 // (we already have the handle from the main task check above).
57 // Host: pass a stack buffer for pthread_getname_np to write into.
58#if defined(USE_ESP32) || defined(USE_LIBRETINY)
59 const char *thread_name = get_thread_name_(current_task);
60#elif defined(USE_ZEPHYR)
61 char thread_name_buf[MAX_POINTER_REPRESENTATION];
62 const char *thread_name = get_thread_name_(thread_name_buf, current_task);
63#else // USE_HOST
64 char thread_name_buf[THREAD_NAME_BUF_SIZE];
65 const char *thread_name = this->get_thread_name_(thread_name_buf);
66#endif
67 this->log_vprintf_non_main_thread_(level, tag, line, format, args, thread_name);
68}
69
70// Handles non-main thread logging only
71// Kept separate from hot path to improve instruction cache performance
72void Logger::log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
73 const char *thread_name) {
74 // Check if already in recursion for this non-main thread/task
75 if (this->is_non_main_task_recursive_()) {
76 return;
77 }
78
79 // RAII guard - automatically resets on any return path
80 auto guard = this->make_non_main_task_guard_();
81
82 bool message_sent = false;
83#ifdef USE_ESPHOME_TASK_LOG_BUFFER
84 // For non-main threads/tasks, queue the message for callbacks
85 message_sent =
86 this->log_buffer_.send_message_thread_safe(level, tag, static_cast<uint16_t>(line), thread_name, format, args);
87 if (message_sent) {
88 // Enable logger loop to process the buffered message
89 // This is safe to call from any context including ISRs
91 }
92#endif
93 // Emergency console logging for non-main threads when ring buffer is full or disabled
94 // This is a fallback mechanism to ensure critical log messages are visible
95 // Note: This may cause interleaved/corrupted console output if multiple threads
96 // log simultaneously, but it's better than losing important messages entirely
97#ifdef USE_HOST
98 if (!message_sent)
99#else
100 if (!message_sent && this->baud_rate_ > 0) // If logging is enabled, write to console
101#endif
102 {
103#ifdef USE_HOST
104 // Host always has console output - no baud_rate check needed
105 static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 512;
106#else
107 // Maximum size for console log messages (includes null terminator)
108 static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 144;
109#endif
110 char console_buffer[MAX_CONSOLE_LOG_MSG_SIZE]; // MUST be stack allocated for thread safety
111 LogBuffer buf{console_buffer, MAX_CONSOLE_LOG_MSG_SIZE};
112 this->format_log_to_buffer_with_terminator_(level, tag, line, format, args, buf, thread_name);
113 this->write_to_console_(buf);
114 }
115
116 // RAII guard automatically resets on return
117}
118#else
119// Implementation for single-task platforms (ESP8266, RP2040)
120// Logging calls are NOT thread-safe: global_recursion_guard_ is a plain bool and tx_buffer_ has no locking.
121// Not a problem in practice yet since Zephyr has no API support (logs are console-only).
122void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args) { // NOLINT
123 if (level > this->level_for(tag) || global_recursion_guard_)
124 return;
125 // Other single-task platforms don't have thread names, so pass nullptr
126 this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
127}
128#endif // USE_ESP32 || USE_HOST || USE_LIBRETINY || USE_ZEPHYR
129
130#ifdef USE_ESP8266
131// ESP8266 keeps log format strings in flash.
132//
133// This function handles format strings stored in flash memory (PROGMEM) to save RAM.
134// Uses vsnprintf_P to read the format string directly from flash without copying to RAM.
135//
136void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format,
137 va_list args) { // NOLINT
138 if (level > this->level_for(tag) || global_recursion_guard_)
139 return;
140
141 this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
142}
143#endif // USE_ESP8266
144
145inline uint8_t Logger::level_for(const char *tag) {
146#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
147 // Skip the lookup when no per-tag levels are set
148 if (this->log_levels_.empty())
149 return this->current_level_;
150 auto it = this->log_levels_.find(FlashTag{tag});
151 if (it != this->log_levels_.end())
152 return it->second;
153#endif
154 return this->current_level_;
155}
156
157Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
158#if defined(USE_ESP32) || defined(USE_LIBRETINY)
159 this->main_task_ = xTaskGetCurrentTaskHandle();
160#elif defined(USE_ZEPHYR)
161 this->main_task_ = k_current_get();
162#elif defined(USE_HOST)
163 this->main_thread_ = pthread_self();
164#endif
165}
166
167#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
169 this->process_messages_();
170#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
171 this->cdc_loop_();
172#endif
173}
174#endif
175
177#ifdef USE_ESPHOME_TASK_LOG_BUFFER
178 // Process any buffered messages when available
179 if (this->log_buffer_.has_messages()) {
180 // Prevent main-task logs emitted by listener callbacks (e.g. the API send path) from re-entering
181 // and corrupting the shared tx_buffer_ / API shared_write_buffer_ while we are draining here.
182 // Mirrors the guard held by log_message_to_buffer_and_send_ on the synchronous logging path.
185 uint16_t text_length;
186 while (this->log_buffer_.borrow_message_main_loop(message, text_length)) {
187 const char *thread_name = message->thread_name[0] != '\0' ? message->thread_name : nullptr;
188 LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
189 this->format_buffered_message_and_notify_(message->level, message->tag, message->line, thread_name,
190 message->text_data(), text_length, buf);
191 // Release the message to allow other tasks to use it as soon as possible
194 }
195 }
196#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
197 else {
198 // No messages to process, disable loop if appropriate
199 // This reduces overhead when there's no async logging activity
201 }
202#endif
203#endif // USE_ESPHOME_TASK_LOG_BUFFER
204}
205
206#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
207void Logger::set_log_level(const char *tag, uint8_t log_level) { this->log_levels_[tag] = log_level; }
208#endif
209
210// Log level strings - packed into flash on ESP8266, indexed by log level (0-7)
211PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE");
212
213static const LogString *get_log_level_str(uint8_t level) {
214 return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
215}
216
218 ESP_LOGCONFIG(TAG,
219 "Logger:\n"
220 " Max Level: %s\n"
221 " Initial Level: %s",
222 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)),
223 LOG_STR_ARG(get_log_level_str(this->current_level_)));
224#ifndef USE_HOST
225 ESP_LOGCONFIG(TAG,
226 " Log Baud Rate: %" PRIu32 "\n"
227 " Hardware UART: %s",
228 this->baud_rate_, LOG_STR_ARG(get_uart_selection_()));
229#endif
230#ifdef USE_ESPHOME_TASK_LOG_BUFFER
231#ifdef USE_HOST
232 ESP_LOGCONFIG(TAG, " Task Log Buffer Slots: %u", static_cast<unsigned int>(this->log_buffer_.size()));
233#else
234 ESP_LOGCONFIG(TAG, " Task Log Buffer Size: %u bytes", static_cast<unsigned int>(this->log_buffer_.size()));
235#endif
236#endif
237
238#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
239 for (auto &it : this->log_levels_) {
240 ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.first, LOG_STR_ARG(get_log_level_str(it.second)));
241 }
242#endif
243#ifdef USE_ZEPHYR
244 dump_crash_();
245 if (!device_is_ready(this->uart_dev_)) {
246 ESP_LOGE(TAG, " %s is not ready.", LOG_STR_ARG(get_uart_selection_()));
247 }
248#endif
249 // Warn users that VERBOSE/VERY_VERBOSE logging impacts performance.
250 // Only the compiled log level matters — all log calls up to this level
251 // are in the binary and will be formatted (vsnprintf) and block UART.
252#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
253 ESP_LOGW(TAG, "VERY_VERBOSE logging is active — significant performance impact, short-term debugging only\n"
254 " May cause connection instability. Set log level to DEBUG or lower for long-term use.");
255#elif ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
256 ESP_LOGI(TAG, "VERBOSE logging is active — performance impact, short-term debugging only\n"
257 " Set log level to DEBUG or lower for long-term use.");
258#endif
259}
260
261void Logger::set_log_level(uint8_t level) {
262 if (level > ESPHOME_LOG_LEVEL) {
263 level = ESPHOME_LOG_LEVEL;
264 ESP_LOGW(TAG, "Cannot set log level higher than pre-compiled %s",
265 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)));
266 }
267 this->current_level_ = level;
268#ifdef USE_LOGGER_LEVEL_LISTENERS
269 for (auto *listener : this->level_listeners_)
270 listener->on_log_level_change(level);
271#endif
272}
273
274Logger *global_logger = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
275
276} // 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
const char *HOT get_thread_name_()
Definition logger.h:397
void dump_config() override
Definition logger.cpp:217
bool HOT is_non_main_task_recursive_() const
Definition logger.h:451
NonMainTaskRecursionGuard make_non_main_task_guard_()
Definition logger.h:454
const LogString * get_uart_selection_()
uint8_t level_for(const char *tag)
Definition logger.cpp:145
void loop() override
Definition logger.cpp:168
void log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args)
Definition logger.cpp:26
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:287
char tx_buffer_[ESPHOME_LOGGER_TX_BUFFER_SIZE+1]
Definition logger.h:375
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:306
std::map< const char *, uint8_t, CStrCompare > log_levels_
Definition logger.h:348
pthread_t main_thread_
Definition logger.h:332
std::vector< LoggerLevelListener * > level_listeners_
Definition logger.h:355
void disable_loop_when_buffer_empty_()
Definition logger.h:477
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:246
void HOT write_log_buffer_to_console_(LogBuffer &buf)
Definition logger.h:278
void set_log_level(uint8_t level)
Set the default log level for this logger.
Definition logger.cpp:261
void HOT write_to_console_(LogBuffer &buf)
Definition logger.h:272
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:72
logger::TaskLogBuffer log_buffer_
Definition logger.h:377
bool main_task_recursion_guard_
Definition logger.h:366
const device * uart_dev_
Definition logger.h:326
Logger(uint32_t baud_rate)
Definition logger.cpp:157
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:274
PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE")
static void uint32_t