ESPHome 2026.11.0-dev
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
11ESPHOME_LOG_TAG(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
145uint8_t Logger::get_log_level(const char *tag) { return this->level_for(tag); }
146
147inline uint8_t Logger::level_for(const char *tag) {
148#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
149 // Skip the lookup when no per-tag levels are set
150 if (this->log_levels_.empty())
151 return this->current_level_;
152 auto it = this->log_levels_.find(FlashTag{tag});
153 if (it != this->log_levels_.end())
154 return it->second;
155#endif
156 return this->current_level_;
157}
158
159Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
160#if defined(USE_ESP32) || defined(USE_LIBRETINY)
161 this->main_task_ = xTaskGetCurrentTaskHandle();
162#elif defined(USE_ZEPHYR)
163 this->main_task_ = k_current_get();
164#elif defined(USE_HOST)
165 this->main_thread_ = pthread_self();
166#endif
167}
168
169#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
171 this->process_messages_();
172#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
173 this->cdc_loop_();
174#endif
175}
176#endif
177
179#ifdef USE_ESPHOME_TASK_LOG_BUFFER
180 // Process any buffered messages when available
181 if (this->log_buffer_.has_messages()) {
182 // Prevent main-task logs emitted by listener callbacks (e.g. the API send path) from re-entering
183 // and corrupting the shared tx_buffer_ / API shared_write_buffer_ while we are draining here.
184 // Mirrors the guard held by log_message_to_buffer_and_send_ on the synchronous logging path.
187 uint16_t text_length;
188 while (this->log_buffer_.borrow_message_main_loop(message, text_length)) {
189 const char *thread_name = message->thread_name[0] != '\0' ? message->thread_name : nullptr;
190 LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
191 this->format_buffered_message_and_notify_(message->level, message->tag, message->line, thread_name,
192 message->text_data(), text_length, buf);
193 // Release the message to allow other tasks to use it as soon as possible
196 }
197 }
198#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
199 else {
200 // No messages to process, disable loop if appropriate
201 // This reduces overhead when there's no async logging activity
203 }
204#endif
205#endif // USE_ESPHOME_TASK_LOG_BUFFER
206}
207
208#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
209void Logger::set_log_level(const char *tag, uint8_t log_level) { this->log_levels_[tag] = log_level; }
210#endif
211
212// Log level strings - packed into flash on ESP8266, indexed by log level (0-7)
213PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE");
214
215static const LogString *get_log_level_str(uint8_t level) {
216 return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
217}
218
220 ESP_LOGCONFIG(TAG,
221 "Logger:\n"
222 " Max Level: %s\n"
223 " Initial Level: %s",
224 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)),
225 LOG_STR_ARG(get_log_level_str(this->current_level_)));
226#ifndef USE_HOST
227 ESP_LOGCONFIG(TAG,
228 " Log Baud Rate: %" PRIu32 "\n"
229 " Hardware UART: %s",
230 this->baud_rate_, LOG_STR_ARG(get_uart_selection_()));
231#endif
232#ifdef USE_ESPHOME_TASK_LOG_BUFFER
233#ifdef USE_HOST
234 ESP_LOGCONFIG(TAG, " Task Log Buffer Slots: %u", static_cast<unsigned int>(this->log_buffer_.size()));
235#else
236 ESP_LOGCONFIG(TAG, " Task Log Buffer Size: %u bytes", static_cast<unsigned int>(this->log_buffer_.size()));
237#endif
238#endif
239
240#ifdef USE_LOGGER_RUNTIME_TAG_LEVELS
241 for (auto &it : this->log_levels_) {
242 ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.first, LOG_STR_ARG(get_log_level_str(it.second)));
243 }
244#endif
245#ifdef USE_ZEPHYR
246 dump_crash_();
247 if (!device_is_ready(this->uart_dev_)) {
248 ESP_LOGE(TAG, " %s is not ready.", LOG_STR_ARG(get_uart_selection_()));
249 }
250#endif
251 // Warn users that VERBOSE/VERY_VERBOSE logging impacts performance.
252 // Only the compiled log level matters — all log calls up to this level
253 // are in the binary and will be formatted (vsnprintf) and block UART.
254#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
255 ESP_LOGW(TAG, "VERY_VERBOSE logging is active — significant performance impact, short-term debugging only\n"
256 " May cause connection instability. Set log level to DEBUG or lower for long-term use.");
257#elif ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
258 ESP_LOGI(TAG, "VERBOSE logging is active — performance impact, short-term debugging only\n"
259 " Set log level to DEBUG or lower for long-term use.");
260#endif
261}
262
263void Logger::set_log_level(uint8_t level) {
264 if (level > ESPHOME_LOG_LEVEL) {
265 level = ESPHOME_LOG_LEVEL;
266 ESP_LOGW(TAG, "Cannot set log level higher than pre-compiled %s",
267 LOG_STR_ARG(get_log_level_str(ESPHOME_LOG_LEVEL)));
268 }
269 this->current_level_ = level;
270#ifdef USE_LOGGER_LEVEL_LISTENERS
271 for (auto *listener : this->level_listeners_)
272 listener->on_log_level_change(level);
273#endif
274}
275
276Logger *global_logger = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
277
278} // 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:399
void dump_config() override
Definition logger.cpp:219
bool HOT is_non_main_task_recursive_() const
Definition logger.h:453
NonMainTaskRecursionGuard make_non_main_task_guard_()
Definition logger.h:456
const LogString * get_uart_selection_()
uint8_t level_for(const char *tag)
Definition logger.cpp:147
void loop() override
Definition logger.cpp:170
uint8_t get_log_level()
Definition logger.h:180
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:289
char tx_buffer_[ESPHOME_LOGGER_TX_BUFFER_SIZE+1]
Definition logger.h:377
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:308
std::map< const char *, uint8_t, CStrCompare > log_levels_
Definition logger.h:350
pthread_t main_thread_
Definition logger.h:334
std::vector< LoggerLevelListener * > level_listeners_
Definition logger.h:357
void disable_loop_when_buffer_empty_()
Definition logger.h:479
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:248
void HOT write_log_buffer_to_console_(LogBuffer &buf)
Definition logger.h:280
void set_log_level(uint8_t level)
Set the default log level for this logger.
Definition logger.cpp:263
void HOT write_to_console_(LogBuffer &buf)
Definition logger.h:274
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:379
bool main_task_recursion_guard_
Definition logger.h:368
const device * uart_dev_
Definition logger.h:328
Logger(uint32_t baud_rate)
Definition logger.cpp:159
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:276
PROGMEM_STRING_TABLE(LogLevelStrings, "NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE")
ESPHOME_LOG_TAG(TAG, "logger")
static void uint32_t