ESPHome 2025.12.2
Loading...
Searching...
No Matches
esphome_syslog.cpp
Go to the documentation of this file.
1#include "esphome_syslog.h"
2
5#include "esphome/core/time.h"
6
7namespace esphome {
8namespace syslog {
9
10// Map log levels to syslog severity using an array, indexed by ESPHome log level (1-7)
12 3, // NONE
13 3, // ERROR
14 4, // WARN
15 5, // INFO
16 6, // CONFIG
17 7, // DEBUG
18 7, // VERBOSE
19 7 // VERY_VERBOSE
20};
21
23
24void Syslog::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
25 this->log_(level, tag, message, message_len);
26}
27
28void Syslog::log_(const int level, const char *tag, const char *message, size_t message_len) const {
29 if (level > this->log_level_)
30 return;
31 // Syslog PRI calculation: facility * 8 + severity
32 int severity = 7;
33 if ((unsigned) level <= 7) {
34 severity = LOG_LEVEL_TO_SYSLOG_SEVERITY[level];
35 }
36 int pri = this->facility_ * 8 + severity;
37 auto now = this->time_->now();
38 std::string timestamp;
39 if (now.is_valid()) {
40 timestamp = now.strftime("%b %e %H:%M:%S");
41 } else {
42 // RFC 5424: A syslog application MUST use the NILVALUE as TIMESTAMP if the syslog application is incapable of
43 // obtaining system time.
44 timestamp = "-";
45 }
46 size_t len = message_len;
47 // remove color formatting
48 if (this->strip_ && message[0] == 0x1B && len > 11) {
49 message += 7;
50 len -= 11;
51 }
52
53 auto data = str_sprintf("<%d>%s %s %s: %.*s", pri, timestamp.c_str(), App.get_name().c_str(), tag, len, message);
54 this->parent_->send_packet((const uint8_t *) data.data(), data.size());
55}
56
57} // namespace syslog
58} // namespace esphome
const std::string & get_name() const
Get the name of this Application set by pre_setup().
void add_log_listener(LogListener *listener)
Register a log listener to receive log messages.
Definition logger.h:218
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override
time::RealTimeClock * time_
void log_(int level, const char *tag, const char *message, size_t message_len) const
ESPTime now()
Get the time in the currently defined timezone.
void send_packet(const uint8_t *data, size_t size)
const char * message
Definition component.cpp:38
Logger * global_logger
Definition logger.cpp:297
constexpr int LOG_LEVEL_TO_SYSLOG_SEVERITY[]
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:503
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:222
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t timestamp
Definition tt21100.cpp:2