ESPHome  2023.5.5
logger.cpp
Go to the documentation of this file.
1 #include "logger.h"
2 #include <cinttypes>
3 
4 #ifdef USE_ESP_IDF
5 #include <driver/uart.h>
6 #include "freertos/FreeRTOS.h"
7 #endif // USE_ESP_IDF
8 
9 #if defined(USE_ESP32_FRAMEWORK_ARDUINO) || defined(USE_ESP_IDF)
10 #include <esp_log.h>
11 #endif // USE_ESP32_FRAMEWORK_ARDUINO || USE_ESP_IDF
12 #include "esphome/core/hal.h"
13 #include "esphome/core/log.h"
14 
15 namespace esphome {
16 namespace logger {
17 
18 static const char *const TAG = "logger";
19 
20 static const char *const LOG_LEVEL_COLORS[] = {
21  "", // NONE
22  ESPHOME_LOG_BOLD(ESPHOME_LOG_COLOR_RED), // ERROR
23  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_YELLOW), // WARNING
24  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GREEN), // INFO
25  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_MAGENTA), // CONFIG
26  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_CYAN), // DEBUG
27  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GRAY), // VERBOSE
28  ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_WHITE), // VERY_VERBOSE
29 };
30 static const char *const LOG_LEVEL_LETTERS[] = {
31  "", // NONE
32  "E", // ERROR
33  "W", // WARNING
34  "I", // INFO
35  "C", // CONFIG
36  "D", // DEBUG
37  "V", // VERBOSE
38  "VV", // VERY_VERBOSE
39 };
40 
41 void Logger::write_header_(int level, const char *tag, int line) {
42  if (level < 0)
43  level = 0;
44  if (level > 7)
45  level = 7;
46 
47  const char *color = LOG_LEVEL_COLORS[level];
48  const char *letter = LOG_LEVEL_LETTERS[level];
49  this->printf_to_buffer_("%s[%s][%s:%03u]: ", color, letter, tag, line);
50 }
51 
52 void HOT Logger::log_vprintf_(int level, const char *tag, int line, const char *format, va_list args) { // NOLINT
53  if (level > this->level_for(tag) || recursion_guard_)
54  return;
55 
56  recursion_guard_ = true;
57  this->reset_buffer_();
58  this->write_header_(level, tag, line);
59  this->vprintf_to_buffer_(format, args);
60  this->write_footer_();
61  this->log_message_(level, tag);
62  recursion_guard_ = false;
63 }
64 #ifdef USE_STORE_LOG_STR_IN_FLASH
65 void Logger::log_vprintf_(int level, const char *tag, int line, const __FlashStringHelper *format,
66  va_list args) { // NOLINT
67  if (level > this->level_for(tag) || recursion_guard_)
68  return;
69 
70  recursion_guard_ = true;
71  this->reset_buffer_();
72  // copy format string
73  auto *format_pgm_p = reinterpret_cast<const uint8_t *>(format);
74  size_t len = 0;
75  char ch = '.';
76  while (!this->is_buffer_full_() && ch != '\0') {
77  this->tx_buffer_[this->tx_buffer_at_++] = ch = (char) progmem_read_byte(format_pgm_p++);
78  }
79  // Buffer full form copying format
80  if (this->is_buffer_full_())
81  return;
82 
83  // length of format string, includes null terminator
84  uint32_t offset = this->tx_buffer_at_;
85 
86  // now apply vsnprintf
87  this->write_header_(level, tag, line);
88  this->vprintf_to_buffer_(this->tx_buffer_, args);
89  this->write_footer_();
90  this->log_message_(level, tag, offset);
91  recursion_guard_ = false;
92 }
93 #endif
94 
95 int HOT Logger::level_for(const char *tag) {
96  // Uses std::vector<> for low memory footprint, though the vector
97  // could be sorted to minimize lookup times. This feature isn't used that
98  // much anyway so it doesn't matter too much.
99  for (auto &it : this->log_levels_) {
100  if (it.tag == tag) {
101  return it.level;
102  }
103  }
104  return ESPHOME_LOG_LEVEL;
105 }
106 void HOT Logger::log_message_(int level, const char *tag, int offset) {
107  // remove trailing newline
108  if (this->tx_buffer_[this->tx_buffer_at_ - 1] == '\n') {
109  this->tx_buffer_at_--;
110  }
111  // make sure null terminator is present
112  this->set_null_terminator_();
113 
114  const char *msg = this->tx_buffer_ + offset;
115  if (this->baud_rate_ > 0) {
116 #ifdef USE_ARDUINO
117  this->hw_serial_->println(msg);
118 #endif // USE_ARDUINO
119 #ifdef USE_ESP_IDF
120  if (
121 #if defined(USE_ESP32_VARIANT_ESP32S2)
123 #elif defined(USE_ESP32_VARIANT_ESP32C3)
125 #elif defined(USE_ESP32_VARIANT_ESP32S3)
127 #else
128  /* DISABLES CODE */ (false)
129 #endif
130  ) {
131  puts(msg);
132  } else {
133  uart_write_bytes(uart_num_, msg, strlen(msg));
134  uart_write_bytes(uart_num_, "\n", 1);
135  }
136 #endif
137  }
138 
139 #ifdef USE_ESP32
140  // Suppress network-logging if memory constrained, but still log to serial
141  // ports. In some configurations (eg BLE enabled) there may be some transient
142  // memory exhaustion, and trying to log when OOM can lead to a crash. Skipping
143  // here usually allows the stack to recover instead.
144  // See issue #1234 for analysis.
145  if (xPortGetFreeHeapSize() < 2048)
146  return;
147 #endif
148 #ifdef USE_HOST
149  puts(msg);
150 #endif
151 
152  this->log_callback_.call(level, tag, msg);
153 }
154 
155 Logger::Logger(uint32_t baud_rate, size_t tx_buffer_size) : baud_rate_(baud_rate), tx_buffer_size_(tx_buffer_size) {
156  // add 1 to buffer size for null terminator
157  this->tx_buffer_ = new char[this->tx_buffer_size_ + 1]; // NOLINT
158 }
159 
161  if (this->baud_rate_ > 0) {
162 #ifdef USE_ARDUINO
163  switch (this->uart_) {
165 #ifdef USE_ESP8266
167 #endif
168 #ifdef USE_RP2040
169  this->hw_serial_ = &Serial1;
170  Serial1.begin(this->baud_rate_);
171 #else
172  this->hw_serial_ = &Serial;
173  Serial.begin(this->baud_rate_);
174 #endif
175 #ifdef USE_ESP8266
176  if (this->uart_ == UART_SELECTION_UART0_SWAP) {
177  Serial.swap();
178  }
179  Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
180 #endif
181  break;
183 #ifdef USE_RP2040
184  this->hw_serial_ = &Serial2;
185  Serial2.begin(this->baud_rate_);
186 #else
187  this->hw_serial_ = &Serial1;
188  Serial1.begin(this->baud_rate_);
189 #endif
190 #ifdef USE_ESP8266
191  Serial1.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
192 #endif
193  break;
194 #if defined(USE_ESP32) && !defined(USE_ESP32_VARIANT_ESP32C3) && !defined(USE_ESP32_VARIANT_ESP32S2) && \
195  !defined(USE_ESP32_VARIANT_ESP32S3)
197  this->hw_serial_ = &Serial2;
198  Serial2.begin(this->baud_rate_);
199  break;
200 #endif
201 #ifdef USE_RP2040
203  this->hw_serial_ = &Serial;
204  Serial.begin(this->baud_rate_);
205  break;
206 #endif
207  }
208 #endif // USE_ARDUINO
209 #ifdef USE_ESP_IDF
210  uart_num_ = UART_NUM_0;
211  switch (uart_) {
213  uart_num_ = UART_NUM_0;
214  break;
216  uart_num_ = UART_NUM_1;
217  break;
218 #if !defined(USE_ESP32_VARIANT_ESP32C3) && !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
220  uart_num_ = UART_NUM_2;
221  break;
222 #endif // !USE_ESP32_VARIANT_ESP32C3 && !USE_ESP32_VARIANT_ESP32S2 && !USE_ESP32_VARIANT_ESP32S3
223 #if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
225  uart_num_ = -1;
226  break;
227 #endif // USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3
228 #if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S3)
230  uart_num_ = -1;
231  break;
232 #endif // USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32S3
233  }
234  if (uart_num_ >= 0) {
235  uart_config_t uart_config{};
236  uart_config.baud_rate = (int) baud_rate_;
237  uart_config.data_bits = UART_DATA_8_BITS;
238  uart_config.parity = UART_PARITY_DISABLE;
239  uart_config.stop_bits = UART_STOP_BITS_1;
240  uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
241  uart_param_config(uart_num_, &uart_config);
242  const int uart_buffer_size = tx_buffer_size_;
243  // Install UART driver using an event queue here
244  uart_driver_install(uart_num_, uart_buffer_size, uart_buffer_size, 10, nullptr, 0);
245  }
246 #endif // USE_ESP_IDF
247  }
248 #ifdef USE_ESP8266
249  else {
250  uart_set_debug(UART_NO);
251  }
252 #endif // USE_ESP8266
253 
254  global_logger = this;
255 #if defined(USE_ESP_IDF) || defined(USE_ESP32_FRAMEWORK_ARDUINO)
256  esp_log_set_vprintf(esp_idf_log_vprintf_);
257  if (ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE) {
258  esp_log_level_set("*", ESP_LOG_VERBOSE);
259  }
260 #endif // USE_ESP_IDF || USE_ESP32_FRAMEWORK_ARDUINO
261 
262  ESP_LOGI(TAG, "Log initialized");
263 }
264 void Logger::set_baud_rate(uint32_t baud_rate) { this->baud_rate_ = baud_rate; }
265 void Logger::set_log_level(const std::string &tag, int log_level) {
266  this->log_levels_.push_back(LogLevelOverride{tag, log_level});
267 }
268 
269 #if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040)
270 UARTSelection Logger::get_uart() const { return this->uart_; }
271 #endif
272 
273 void Logger::add_on_log_callback(std::function<void(int, const char *, const char *)> &&callback) {
274  this->log_callback_.add(std::move(callback));
275 }
276 float Logger::get_setup_priority() const { return setup_priority::BUS + 500.0f; }
277 const char *const LOG_LEVELS[] = {"NONE", "ERROR", "WARN", "INFO", "CONFIG", "DEBUG", "VERBOSE", "VERY_VERBOSE"};
278 #ifdef USE_ESP32
279 const char *const UART_SELECTIONS[] = {
280  "UART0", "UART1",
281 #if !defined(USE_ESP32_VARIANT_ESP32C3) && !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
282  "UART2",
283 #endif // !USE_ESP32_VARIANT_ESP32C3 && !USE_ESP32_VARIANT_ESP32S2 && !USE_ESP32_VARIANT_ESP32S3
284 #if defined(USE_ESP_IDF)
285 #if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
286  "USB_CDC",
287 #endif // USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3
288 #if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S3)
289  "USB_SERIAL_JTAG",
290 #endif // USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32S3
291 #endif // USE_ESP_IDF
292 };
293 #endif // USE_ESP32
294 #ifdef USE_ESP8266
295 const char *const UART_SELECTIONS[] = {"UART0", "UART1", "UART0_SWAP"};
296 #endif
297 #ifdef USE_RP2040
298 const char *const UART_SELECTIONS[] = {"UART0", "UART1", "USB_CDC"};
299 #endif // USE_ESP8266
301  ESP_LOGCONFIG(TAG, "Logger:");
302  ESP_LOGCONFIG(TAG, " Level: %s", LOG_LEVELS[ESPHOME_LOG_LEVEL]);
303  ESP_LOGCONFIG(TAG, " Log Baud Rate: %" PRIu32, this->baud_rate_);
304 #if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040)
305  ESP_LOGCONFIG(TAG, " Hardware UART: %s", UART_SELECTIONS[this->uart_]);
306 #endif
307 
308  for (auto &it : this->log_levels_) {
309  ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.tag.c_str(), LOG_LEVELS[it.level]);
310  }
311 }
312 void Logger::write_footer_() { this->write_to_buffer_(ESPHOME_LOG_RESET_COLOR, strlen(ESPHOME_LOG_RESET_COLOR)); }
313 
314 Logger *global_logger = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
315 
316 } // namespace logger
317 } // namespace esphome
void set_baud_rate(uint32_t baud_rate)
Manually set the baud rate for serial, set to 0 to disable.
Definition: logger.cpp:264
void add_on_log_callback(std::function< void(int, const char *, const char *)> &&callback)
Register a callback that will be called for every log message sent.
Definition: logger.cpp:273
UARTSelection
Enum for logging UART selection.
Definition: logger.h:33
int level_for(const char *tag)
Definition: logger.cpp:95
void log_vprintf_(int level, const char *tag, int line, const char *format, va_list args)
Definition: logger.cpp:52
void vprintf_to_buffer_(const char *format, va_list args)
Definition: logger.h:119
void dump_config() override
Definition: logger.cpp:300
float get_setup_priority() const override
Definition: logger.cpp:276
Logger(uint32_t baud_rate, size_t tx_buffer_size)
Definition: logger.cpp:155
void write_header_(int level, const char *tag, int line)
Definition: logger.cpp:41
Logger * global_logger
Definition: logger.cpp:314
uart_port_t uart_num_
Definition: logger.h:152
const float BUS
For communication buses like i2c/spi.
Definition: component.cpp:15
UARTSelection get_uart() const
Get the UART used by the logger.
Definition: logger.cpp:270
void set_null_terminator_()
Definition: logger.h:106
void printf_to_buffer_(const char *format,...)
Definition: logger.h:134
void write_to_buffer_(char value)
Definition: logger.h:110
const char *const LOG_LEVELS[]
Definition: logger.cpp:277
UARTSelection uart_
Definition: logger.h:146
void pre_setup()
Set up this component.
Definition: logger.cpp:160
uint8_t progmem_read_byte(const uint8_t *addr)
Definition: core.cpp:57
std::string size_t len
Definition: helpers.h:286
const char *const UART_SELECTIONS[]
Definition: logger.cpp:279
void log_message_(int level, const char *tag, int offset=0)
Definition: logger.cpp:106
Definition: a4988.cpp:4
std::vector< LogLevelOverride > log_levels_
Definition: logger.h:158
void set_log_level(const std::string &tag, int log_level)
Set the log level of the specified tag.
Definition: logger.cpp:265
bool recursion_guard_
Prevents recursive log calls, if true a log message is already being processed.
Definition: logger.h:161
CallbackManager< void(int, const char *, const char *)> log_callback_
Definition: logger.h:159
int HOT esp_idf_log_vprintf_(const char *format, va_list args)
Definition: log.cpp:50
bool is_buffer_full_() const
Definition: logger.h:103