ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
log_buffer.h
Go to the documentation of this file.
1#pragma once
2
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
7
8namespace esphome::logger {
9
10// Space write_header() needs free. Without the tag the header takes at most 68 bytes (20 fixed, 48 for a thread name
11// of up to MAX_TAG_LENGTH); the tag gets the rest of the line's room minus that budget, so at least MAX_TAG_LENGTH
12// (on ESP8266 exactly MAX_TAG_LENGTH)
13static constexpr uint16_t MAX_HEADER_SIZE = 128;
14// Longest thread name in the header, and the shortest tag it always keeps
15static constexpr size_t MAX_TAG_LENGTH = 32;
16
17// ANSI color code last digit (30-38 range, store only last digit to save RAM on ESP8266)
18static const char LOG_LEVEL_COLOR_DIGIT[] PROGMEM = {
19 '\0', // NONE
20 '1', // ERROR (31 = red)
21 '3', // WARNING (33 = yellow)
22 '2', // INFO (32 = green)
23 '5', // CONFIG (35 = magenta)
24 '6', // DEBUG (36 = cyan)
25 '7', // VERBOSE (37 = gray)
26 '8', // VERY_VERBOSE (38 = white)
27};
28
29static const char LOG_LEVEL_LETTER_CHARS[] PROGMEM = {
30 '\0', // NONE
31 'E', // ERROR
32 'W', // WARNING
33 'I', // INFO
34 'C', // CONFIG
35 'D', // DEBUG
36 'V', // VERBOSE (VERY_VERBOSE uses two 'V's)
37};
38
39// Buffer wrapper for log formatting functions
40struct LogBuffer {
41 char *data;
42 uint16_t size;
43 uint16_t pos{0};
44 // Replaces the null terminator with a newline for console output.
45 // Must be called after notify_listeners_() since listeners need null-terminated strings.
46 // Console output uses length-based writes (buf.pos), so null terminator is not needed.
47 // The body writers keep the terminator's byte inside the buffer, so the newline always fits
48 void terminate_with_newline() { this->data[this->pos++] = '\n'; }
49 void HOT write_header(uint8_t level, const char *tag, int line, const char *thread_name) {
50 // Early return if insufficient space - intentionally don't update pos to prevent partial writes
51 if (this->pos + MAX_HEADER_SIZE > this->size)
52 return;
53
54 char *p = this->current_();
55
56 // Write ANSI color
57 p = write_ansi_color(p, level);
58
59 // Construct: [LEVEL][tag:line]
60 *p++ = '[';
61 if (level != 0) {
62 if (level >= 7) {
63 *p++ = 'V'; // VERY_VERBOSE = "VV"
64 *p++ = 'V';
65 } else {
66 *p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_LETTER_CHARS[level])));
67 }
68 }
69 *p++ = ']';
70 *p++ = '[';
71
72 // Copy tag
73#ifdef USE_ESP8266
74 // ESP8266 has always cut tags at MAX_TAG_LENGTH, which leaves the message more of a short buffer
75 p = copy_string(p, tag, MAX_TAG_LENGTH);
76#else
77 // The early return above leaves at least MAX_HEADER_SIZE, so the tag keeps MAX_TAG_LENGTH or more
78 p = copy_string(p, tag, this->remaining_() - (MAX_HEADER_SIZE - MAX_TAG_LENGTH));
79#endif
80
81 *p++ = ':';
82
83 // Format line number using subtraction loops (no division - important for ESP8266 which lacks hardware divider)
84 if (line > 999) [[unlikely]] {
85 p = write_digit(p, line, 1000);
86 }
87 p = write_digit(p, line, 100);
88 p = write_digit(p, line, 10);
89 *p++ = '0' + line;
90 *p++ = ']';
91
92#if defined(USE_ESP32) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR) || defined(USE_HOST)
93 // Write thread name with bold red color
94 if (thread_name != nullptr) {
95 p = write_ansi_color(p, 1); // Bold red for thread name
96 *p++ = '[';
97 p = copy_string(p, thread_name, MAX_TAG_LENGTH);
98 *p++ = ']';
99 p = write_ansi_color(p, level); // Restore original color
100 }
101#endif
102
103 *p++ = ':';
104 *p++ = ' ';
105
106 this->pos = p - this->data;
107 }
108 void HOT format_body(const char *format, va_list args) {
109 this->format_vsnprintf_(format, args);
110 this->finalize_();
111 }
112#ifdef USE_ESP8266
113 void HOT format_body_p(PGM_P format, va_list args) {
114 this->format_vsnprintf_p_(format, args);
115 this->finalize_();
116 }
117#endif
118 // Writes a message that needs no formatting, truncated and stripped of trailing newlines as format_body() does
119 // Forced inline: as on dev, the per-line path keeps it in its caller instead of calling out on every line
120 inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body(const char *text, size_t len) {
121 const int room = this->body_room_();
122 if (room > 0) {
123 const uint16_t limit = room - 1; // vsnprintf() keeps the last byte for the null terminator
124 const uint16_t copy_len = (len < limit) ? static_cast<uint16_t>(len) : limit;
125 memcpy(this->current_(), text, copy_len);
126 this->pos += copy_len;
127 this->strip_trailing_newlines_();
128 this->write_ansi_reset_();
129 }
130 this->finalize_();
131 }
132 // write_unformatted_body() for a message in flash
133 inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text) {
134 const int room = this->body_room_();
135 if (room > 0) {
136 char *const start = this->current_();
137 this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + room - 1, text) - this->data);
138 this->strip_trailing_newlines_();
139 this->write_ansi_reset_();
140 }
141 this->finalize_();
142 }
143 static constexpr uint16_t ANSI_COLOR_LEN = 7; // "\033[{bold};3{color}m" written by write_header for level != 0
144 static constexpr uint16_t ANSI_RESET_LEN = 4; // "\033[0m"
145 // Largest replay header: color plus "@4294967295ms "
146 static constexpr uint16_t REPLAY_HEADER_MAX_SIZE = ANSI_COLOR_LEN + 1 + 10 + 3;
147 // Color for level followed by the time since boot, in front of a line replayed from the boot log buffer
148 void write_replay_header(uint8_t level, uint32_t ms) {
149 if (this->pos + REPLAY_HEADER_MAX_SIZE > this->size)
150 return;
151 char *p = this->current_();
152 p = write_ansi_color(p, level);
153 *p++ = '@';
154 p = uint32_to_str_unchecked(p, ms);
155 *p++ = 'm';
156 *p++ = 's';
157 *p++ = ' ';
158 this->pos = static_cast<uint16_t>(p - this->data);
159 }
160 // Same as write_unformatted_body(), for the boot replay and the task log buffer
161#ifdef USE_ESP8266
162 // No task log buffer here, so the boot replay is the only caller and takes it inline
163 void write_body(const char *text, uint16_t text_length) { this->write_unformatted_body(text, text_length); }
164#else
165 // One out-of-line copy shared by both callers
166 void __attribute__((noinline)) write_body(const char *text, uint16_t text_length) {
168 }
169#endif
170
171 private:
172 uint16_t remaining_() const { return this->size - this->pos; }
173 // Room for the body and its null terminator with the color reset behind it; 0 or less when there is none
174 int body_room_() const { return this->remaining_() - ANSI_RESET_LEN; }
175 char *current_() { return this->data + this->pos; }
176 // The body starts inside the buffer (write_header() needs MAX_HEADER_SIZE free) and the body writers keep a byte
177 // for the terminator, so pos is inside the buffer here
178 inline void ESPHOME_ALWAYS_INLINE finalize_() { this->data[this->pos] = '\0'; }
179 // Write ANSI reset sequence inline ("\033[0m"); forced inline, since it runs on every log line
180 // Callers have checked body_room_(), which keeps space for the reset and the terminator after it
181 inline void ESPHOME_ALWAYS_INLINE write_ansi_reset_() {
182 char *p = this->current_();
183 *p++ = '\033';
184 *p++ = '[';
185 *p++ = '0';
186 *p++ = 'm';
187 this->pos += ANSI_RESET_LEN;
188 }
189 // Forced inline: an outlined copy slows every formatted line
190 inline void ESPHOME_ALWAYS_INLINE strip_trailing_newlines_() {
191 while (this->pos > 0 && this->data[this->pos - 1] == '\n')
192 this->pos--;
193 }
194 void process_vsnprintf_result_(int ret, int room) {
195 if (ret >= 0) {
196 this->pos += (ret >= room) ? (room - 1) : ret;
197 this->strip_trailing_newlines_();
198 }
199 this->write_ansi_reset_();
200 }
201 void format_vsnprintf_(const char *format, va_list args) {
202 const int room = this->body_room_();
203 if (room <= 0)
204 return;
205 this->process_vsnprintf_result_(vsnprintf(this->current_(), room, format, args), room);
206 }
207#ifdef USE_ESP8266
208 void format_vsnprintf_p_(PGM_P format, va_list args) {
209 const int room = this->body_room_();
210 if (room <= 0)
211 return;
212 this->process_vsnprintf_result_(vsnprintf_P(this->current_(), room, format, args), room);
213 }
214#endif
215 // Extract one decimal digit via subtraction (no division - important for ESP8266)
216 static inline char *ESPHOME_ALWAYS_INLINE write_digit(char *p, int &value, int divisor) {
217 char d = '0';
218 while (value >= divisor) {
219 d++;
220 value -= divisor;
221 }
222 *p++ = d;
223 return p;
224 }
225 // Writes up to 7 bytes unchecked, so the caller reserves space; returns the new end, keeping p in a register
226 static char *write_ansi_color(char *p, uint8_t level) {
227 if (level == 0)
228 return p;
229 // Direct buffer fill: "\033[{bold};3{color}m" (7 bytes)
230 *p++ = '\033';
231 *p++ = '[';
232 *p++ = (level == 1) ? '1' : '0'; // Only ERROR is bold
233 *p++ = ';';
234 *p++ = '3';
235 *p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_COLOR_DIGIT[level])));
236 *p++ = 'm';
237 return p;
238 }
239 // Copies str unchecked and without its null terminator, so the caller reserves space; returns the new end
240 // Copies at most max_len bytes, so the header stays within MAX_HEADER_SIZE and the body starts inside the buffer
241 static inline char *ESPHOME_ALWAYS_INLINE copy_string(char *p, const char *str, size_t max_len) {
242#ifdef USE_ESP8266
243 // Tags may be in PROGMEM
244 p = progmem_copy_str(p, p + max_len, str);
245#else
246 const size_t len = strnlen(str, max_len);
247 memcpy(p, str, len); // NOLINT(bugprone-not-null-terminated-result) - the header is built piece by piece
248 p += len;
249#endif
250 return p;
251 }
252};
253
254} // namespace esphome::logger
int ret
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
char *ESPHOME_ALWAYS_INLINE progmem_copy_str(char *dst, const char *end, const char *src)
Copy a PROGMEM string to dst, stopping at its null terminator or at end, and return the new end of ds...
Definition helpers.h:1549
void const char int line
Definition log.h:110
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:445
void const char int const char * format
Definition log.h:110
void const char * tag
Definition log.h:110
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
static void uint32_t
void HOT format_body_p(PGM_P format, va_list args)
Definition log_buffer.h:113
void write_replay_header(uint8_t level, uint32_t ms)
Definition log_buffer.h:148
static constexpr uint16_t ANSI_COLOR_LEN
Definition log_buffer.h:143
static constexpr uint16_t ANSI_RESET_LEN
Definition log_buffer.h:144
static constexpr uint16_t REPLAY_HEADER_MAX_SIZE
Definition log_buffer.h:146
void write_body(const char *text, uint16_t text_length)
Definition log_buffer.h:163
void HOT write_header(uint8_t level, const char *tag, int line, const char *thread_name)
Definition log_buffer.h:49
void HOT format_body(const char *format, va_list args)
Definition log_buffer.h:108
void __attribute__((noinline)) write_body(const char *text
void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text)
Definition log_buffer.h:133
void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body(const char *text, size_t len)
Definition log_buffer.h:120