Full MQTT topic rebuild per docs/reference/vesper_mqtt_topic_spec_v2.md.
Only the MQTT transport path changed — WebSocket, HTTP, and UART are untouched.
- control/command (in) + control/ack (out, strictly replies) replace the old
control/data pair; new control/reports for critical unsolicited events
(bell overload) that don't belong on the strictly-reply ack channel
- status/playback split out for playback transitions only
- status/alerts + status/info renamed to system/alerts + system/info, both
now correctly retained; new system/logs and system/metrics (diagnostics
report moved here from system/info, gained bell strike/heat data)
- LWT registered for the first time — status/heartbeat gets
{"state":"offline","ok":false} on an unclean disconnect; graceful
disconnect (mqtt.disable) announces offline explicitly since LWT doesn't
fire on a clean disconnect
- heartbeat payload flattened, gains independently-derived state/ok fields
(via a new MQTTDriver::setStateProvider() wired from Player+HealthMonitor)
- optional req_id correlation added bus-wide (CommandEnvelope/CommandResult),
not MQTT-only, since any transport with multiple senders sharing one
channel has the same problem. Always optional — v1 clients unaffected.
- per-topic ON/OFF switches (ConfigManager::MqttTopicConfig, 8 flags) as
sub-switches under the existing mqtt.enable/disable master switch, so a
device can breathe by disabling topics it doesn't need. New
mqtt.get_topics/mqtt.set_topics commands; command switch applies live.
Bumped to v2.2.0. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
12 KiB
Logging
Centralized, subsystem-aware logging layer for Vesper firmware. It routes log messages to up to three independent output channels — Serial (USB), MQTT, and SD card — each with its own configurable log level. Per-subsystem tag overrides let individual subsystems be silenced or restricted on a specific channel without affecting others (e.g. silencing MQTTClient on the MQTT channel to prevent recursion). The class is fully static; there is no instance to manage.
Public API
Log emission
Each .cpp file defines #define TAG "SubsystemName" at the top and calls the macros below. The macros are thin wrappers around the static methods.
| Macro / Method | Description |
|---|---|
LOG_ERROR(tag, fmt, ...) / Logging::error(tag, fmt, ...) |
Emit at ERROR level |
LOG_WARNING(tag, fmt, ...) / Logging::warning(tag, fmt, ...) |
Emit at WARNING level |
LOG_INFO(tag, fmt, ...) / Logging::info(tag, fmt, ...) |
Emit at INFO level |
LOG_DEBUG(tag, fmt, ...) / Logging::debug(tag, fmt, ...) |
Emit at DEBUG level |
LOG_VERBOSE(tag, fmt, ...) / Logging::verbose(tag, fmt, ...) |
Emit at VERBOSE level |
fmt is a printf-style format string. The formatted message is capped at 512 bytes internally for Serial output. Messages routed to MQTT and/or SD are additionally capped at 256 bytes when copied into the deferred-output queue — see Deferred MQTT/SD output below.
Global channel levels
| Method | Description |
|---|---|
Logging::setSerialLevel(level) |
Set baseline level for Serial output |
Logging::setMqttLevel(level) |
Set baseline level for MQTT output |
Logging::setSdLevel(level) |
Set baseline level for SD output |
Logging::getSerialLevel() |
Return current Serial level |
Logging::getMqttLevel() |
Return current MQTT level |
Logging::getSdLevel() |
Return current SD level |
Logging::setLevel(level) |
Legacy alias for setSerialLevel |
Logging::getLevel() |
Legacy alias for getSerialLevel |
Logging::setMqttLogLevel(level) |
Legacy alias for setMqttLevel |
Logging::getMqttLogLevel() |
Legacy alias for getMqttLevel |
Per-subsystem overrides
| Method | Description |
|---|---|
Logging::setSubsystemSerialLevel(tag, level) |
Cap or silence tag on Serial only |
Logging::setSubsystemMqttLevel(tag, level) |
Cap or silence tag on MQTT only |
Logging::setSubsystemSdLevel(tag, level) |
Cap or silence tag on SD only |
Pass Logging::NONE to fully suppress a tag on a channel. The override map is keyed by the exact tag string.
Output channel registration
| Method | Description |
|---|---|
Logging::setMqttPublishCallback(callback, logTopic) |
Register the function used to publish log messages over MQTT, and the topic to publish to |
Logging::setSdWriteCallback(callback) |
Register the function used to append log lines to the SD log file |
Both channels start disabled (callbacks are nullptr). Output on a channel is silenced until the relevant callback is registered.
Deferred MQTT/SD output
MQTT and SD are not written synchronously from the calling task. Logging::log() formats the Serial line as before, but if the message is also enabled for MQTT and/or SD, it copies the tag/level/message into a fixed-size LogQueueItem (message capped at 256 bytes) and hands it to a dedicated LoggingTask via a FreeRTOS queue (depth 16, non-blocking send — a full queue drops the line rather than stalling the caller). LoggingTask is created lazily, on the first message that needs MQTT or SD output, and runs the existing publishToMqtt()/writeToSd() logic on its own 4096-byte stack.
This exists because AsyncMqttClient::publish() and SD file writes are variable-depth, stack-hungry operations. Running them synchronously on whatever task called LOG_* meant a small-stack task doing other stack-heavy work (JSON serialization, SD I/O) could silently overflow — this is exactly what happened to TelemetryTask (see docs/features/feature-catalog.md F-051). Deferring MQTT/SD to their own task means no caller's stack ever has to absorb that cost.
Serial output is deliberately not deferred — it stays synchronous so the USB serial monitor reflects the true, immediate order of events, which matters most when debugging a crash.
MQTT rate limiting
Each subsystem tag has its own token bucket on the MQTT channel: a burst of 10 messages, refilling at 1/second. Once a tag's bucket is empty, further messages from that tag are dropped (not queued) until it refills. This protects the broker/airtime from a chatty or misconfigured subsystem — e.g. a per-subsystem override left at VERBOSE in the field.
Drops are not silent: the next time that tag is allowed to publish again, a WARNING-level summary line is emitted first ("suppressed N log message(s) (MQTT rate limit)"), so a burst is visible even though not every line survived it. Serial and SD channels are unaffected by this limiter — only MQTT.
Utilities
| Method | Description |
|---|---|
Logging::isLevelEnabled(level) |
Returns true if Serial level is at or above level (checks Serial only) |
Logging::levelToString(level) |
Returns a human-readable string for a LogLevel value |
Log levels
| Value | Name | Integer |
|---|---|---|
NONE |
No output | 0 |
ERROR |
Errors only | 1 |
WARNING |
Warnings and errors | 2 |
INFO |
Info, warnings, errors | 3 |
DEBUG |
Debug detail | 4 |
VERBOSE |
Everything | 5 |
Output formats
Serial: [LEVL][Tag] message\n
MQTT payload (JSON):
{"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345}
timestamp is millis() (ms since boot), not wall-clock time.
SD line (plain text): 2026-07-15 | 12:28:04 | 13460843 -> 🔵 [DEBG][Tag] message, written to a day-rotated file — see FileManager. Date/time comes from time(nullptr) (set by NTP via Timekeeper::syncTimeWithNTP(), independent of HAS_RTC) — printed as unset-date | unset-time if no wall clock is available yet. The number after the second | is millis() (uptime in ms), unaffected by wall-clock availability.
Initialization
Logging has no begin() call. Static defaults at startup are:
- Serial:
VERBOSE - MQTT:
NONE - SD:
NONE
Step 1 — Apply Serial level from config (main.cpp, early in setup)
Logging::setLevel((Logging::LogLevel)configManager.getGeneralConfig().serialLogLevel);
This happens immediately after configManager.begin(), before any other subsystem is initialized, so all subsequent boot messages respect the configured level.
Step 2 — Register MQTT and SD callbacks (CommunicationRouter::begin)
CommunicationRouter::begin() registers both callbacks and applies all three channel levels from ConfigManager:
Logging::setMqttPublishCallback(..., mqttClient.getLogsTopic()); // vesper/<uid>/system/logs
Logging::setSdWriteCallback([fm](const String& line) {
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
});
Logging::setSerialLevel(...);
Logging::setMqttLevel(...);
Logging::setSdLevel(...);
The registered MQTT publish callback also checks ConfigManager::getMqttTopicConfig().logs before publishing — this is a second, independent gate alongside the per-level mqttLevel check Logging already does internally. An operator can silence the whole system/logs channel via mqtt.set_topics { "logs": false } without changing the configured level, then re-enable it later with the level untouched. See docs/reference/vesper_mqtt_topic_spec_v2.md.
It also sets the default per-subsystem MQTT suppressions to prevent feedback loops:
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
MQTT and SD output are therefore inactive until CommunicationRouter::begin() runs.
Runtime level changes
LoggingHandler handles the log.set_serial, log.set_mqtt, and log.set_sd commands routed through the CommandBus. These persist the new level to ConfigManager (saved to SD) and apply it immediately.
Command example:
{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 3 } }
Dependencies
| Dependency | Why |
|---|---|
Arduino.h / Serial |
Serial output channel |
ConfigManager |
Reads initial log levels at boot; saves runtime changes |
CommunicationRouter |
Registers the MQTT publish callback and SD write callback |
FileManager |
Provides appendLine() used by the SD callback |
std::map<String, LogLevel> |
Per-subsystem override storage |
Logging.hpp includes <map>, <functional>, and <freertos/FreeRTOS.h>/<freertos/queue.h>. The class lazily creates one dedicated LoggingTask (and its backing queue) the first time a message needs MQTT or SD output.
Gotchas / Notes
Thread safety. The class has no general mutex protection. The per-channel re-entrancy guards (isPublishing, isWriting) are static bool flags, not atomics — harmless now that publishToMqtt()/writeToSd() only ever run from LoggingTask (a single task, so no concurrent entry), but not a general-purpose safety mechanism. The one spot that is protected is LoggingTask/queue creation itself (ensureLoggingTaskStarted()), guarded by a spinlock so two tasks racing to log for the first time can't both create a queue+task. Serial output is still called directly from whatever task logs; its hardware FIFO makes concurrent calls tolerable in practice, but strictly speaking interleaved Serial.printf() calls from multiple tasks are a data race.
MQTT feedback loop. Any subsystem whose logs are emitted on the MQTT channel must not call Logging from within the MQTT publish path. MQTTClient and CommRouter are silenced on MQTT by default for this reason. The isPublishing guard is a secondary safeguard.
MQTT/SD output is deferred to LoggingTask, not run on the calling task. See Deferred MQTT/SD output above. FileManager::appendLogLine's directory scan (every 50th write — see FileManager's log rotation notes) and AsyncMqttClient::publish() now only ever run on LoggingTask's own stack. Calling tasks pay only a vsnprintf into a 512-byte local buffer plus a non-blocking queue send — cheap and fixed-cost regardless of MQTT/SD load.
isLevelEnabled checks Serial only. If you need to guard an expensive log-string build (e.g. formatting a large buffer before calling LOG_DEBUG), use Logging::isLevelEnabled(Logging::DEBUG). Be aware this ignores MQTT and SD levels.
Message truncation. The Serial format buffer is 512 bytes; messages longer than 511 characters are silently truncated by vsnprintf. Messages also routed to MQTT/SD are truncated again to 255 characters when copied into the queue item. Audited against actual LOG_* call sites in the codebase (longest literal format strings ~110 chars; worst realistic case with substitutions ~150–180 chars) — 256 bytes has comfortable margin.
No timestamps beyond millis(). MQTT and SD payloads use millis() (ms since boot). Wall-clock timestamps are not included; correlate with NTP-synced log entries from the backend if absolute time is needed.
MQTT and SD channels are disabled by default. Both callbacks start as nullptr. Messages targeting those channels are dropped silently until CommunicationRouter::begin() registers the callbacks. Any logs emitted before that point (early boot) are Serial-only regardless of configured levels.