Logging::log() previously ran AsyncMqttClient::publish() and SD file writes synchronously on whatever task called LOG_*. Both are variable-depth, stack-hungry operations, and this is what let TelemetryTask's 4096B stack silently absorb enough nested cost to overflow its canary (see feature-catalog.md F-051). Serial output stays synchronous (cheap, and must reflect true event order for crash debugging). MQTT/SD-bound messages are now copied into a fixed-size LogQueueItem (256-byte message cap, audited against real LOG_* call sites — worst case ~150-180 chars, comfortable margin) and handed via non-blocking xQueueSend to a lazily-created LoggingTask, which performs the actual publish/write on its own 4096B stack. A full queue drops the line rather than blocking the caller. Queue+task creation is spinlock-guarded against concurrent first-callers. This removes the stack-nesting risk for every current and future task that logs, not just Telemetry/HealthMonitor — closing the broader risk flagged in F-051 for OutputManager, TimeKeeper, MQTTDriver's own tasks, and Networking's netRecon. Verified via pio run: RAM impact negligible (62980 vs 62956 bytes). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
199 lines
13 KiB
C++
199 lines
13 KiB
C++
/*
|
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
|
* LOGGING.HPP - Subsystem-Aware Centralized Logging System
|
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
|
*
|
|
* 📝 THE INFORMATION CHRONICLER OF VESPER 📝
|
|
*
|
|
* Three independent output channels, each with their own level:
|
|
* • Serial — USB debugging, local connection
|
|
* • MQTT — Remote troubleshooting via web dashboard
|
|
* • SD — Persistent log storage for post-mortem analysis
|
|
*
|
|
* Per-subsystem filtering: each subsystem tag can have its own level
|
|
* overrides per channel. If no override is set, the global channel
|
|
* level applies. Set a tag's level to NONE on a specific channel to
|
|
* silence it entirely on that channel (e.g. MQTT internals on MQTT).
|
|
*
|
|
* Usage in each .cpp file:
|
|
* #define TAG "BellEngine" // one line at the top
|
|
* LOG_INFO(TAG, "Ring scheduled"); // all calls include the tag
|
|
*
|
|
* The JSON payload sent over MQTT includes the subsystem field:
|
|
* {"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345}
|
|
*
|
|
* 📋 VERSION: 3.0 (Subsystem-aware logging)
|
|
* 📅 DATE: 2025
|
|
* 👨💻 AUTHOR: Advanced Bell Systems
|
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
|
*/
|
|
|
|
#ifndef LOGGING_HPP
|
|
#define LOGGING_HPP
|
|
|
|
#include <Arduino.h>
|
|
#include <map>
|
|
#include <functional>
|
|
#include <freertos/FreeRTOS.h>
|
|
#include <freertos/queue.h>
|
|
|
|
class Logging {
|
|
public:
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// LOG LEVELS
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
enum LogLevel {
|
|
NONE = 0, // No output
|
|
ERROR = 1, // Errors only
|
|
WARNING = 2, // Warnings and errors
|
|
INFO = 3, // Info, warnings, errors
|
|
DEBUG = 4, // Debug detail
|
|
VERBOSE = 5 // Everything
|
|
};
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// CALLBACK TYPES
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
using MqttPublishCallback = std::function<void(const String& topic, const String& payload, int qos)>;
|
|
using SdWriteCallback = std::function<void(const String& line)>;
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// GLOBAL CHANNEL LEVELS
|
|
// Set the baseline level for each output channel.
|
|
// Per-subsystem overrides take precedence when set.
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static void setSerialLevel(LogLevel level);
|
|
static void setMqttLevel(LogLevel level);
|
|
static void setSdLevel(LogLevel level);
|
|
|
|
static LogLevel getSerialLevel();
|
|
static LogLevel getMqttLevel();
|
|
static LogLevel getSdLevel();
|
|
|
|
// Legacy compatibility (maps to serial level)
|
|
static void setLevel(LogLevel level) { setSerialLevel(level); }
|
|
static LogLevel getLevel() { return getSerialLevel(); }
|
|
static void setMqttLogLevel(LogLevel level) { setMqttLevel(level); }
|
|
static LogLevel getMqttLogLevel() { return getMqttLevel(); }
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// PER-SUBSYSTEM LEVEL OVERRIDES
|
|
// Call these at startup to silence or focus specific subsystems per channel.
|
|
// Pass NONE to completely silence a subsystem on a channel.
|
|
// Pass a level to cap that subsystem at that level on that channel.
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static void setSubsystemSerialLevel(const char* tag, LogLevel level);
|
|
static void setSubsystemMqttLevel(const char* tag, LogLevel level);
|
|
static void setSubsystemSdLevel(const char* tag, LogLevel level);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// OUTPUT CHANNEL REGISTRATION
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static void setMqttPublishCallback(MqttPublishCallback callback, const String& logTopic);
|
|
static void setSdWriteCallback(SdWriteCallback callback);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// LOGGING FUNCTIONS (tag = subsystem name, e.g. "BellEngine")
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static void error(const char* tag, const char* format, ...);
|
|
static void warning(const char* tag, const char* format, ...);
|
|
static void info(const char* tag, const char* format, ...);
|
|
static void debug(const char* tag, const char* format, ...);
|
|
static void verbose(const char* tag, const char* format, ...);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// UTILITIES
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static bool isLevelEnabled(LogLevel level);
|
|
static String levelToString(LogLevel level);
|
|
|
|
private:
|
|
// Global channel levels
|
|
static LogLevel _serialLevel;
|
|
static LogLevel _mqttLevel;
|
|
static LogLevel _sdLevel;
|
|
|
|
// Per-subsystem overrides per channel (tag -> level)
|
|
// A value of NONE means "suppress this subsystem on this channel entirely"
|
|
static std::map<String, LogLevel> _serialOverrides;
|
|
static std::map<String, LogLevel> _mqttOverrides;
|
|
static std::map<String, LogLevel> _sdOverrides;
|
|
|
|
// Output channel callbacks
|
|
static MqttPublishCallback _mqttCallback;
|
|
static SdWriteCallback _sdCallback;
|
|
static String _mqttLogTopic;
|
|
|
|
// Core internal methods
|
|
static void log(LogLevel level, const char* levelStr, const char* tag, const char* format, va_list args);
|
|
static void publishToMqtt(LogLevel level, const char* levelStr, const char* tag, const char* message);
|
|
static void writeToSd(LogLevel level, const char* levelStr, const char* tag, const char* message);
|
|
|
|
// Resolve effective level for a tag on a channel
|
|
static LogLevel resolveLevel(const char* tag, LogLevel globalLevel, const std::map<String, LogLevel>& overrides);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// DEFERRED OUTPUT (MQTT publish + SD write)
|
|
// Both channels do variable-depth, stack-hungry I/O (AsyncMqttClient::publish(),
|
|
// SD file writes). Running them synchronously on whatever task called LOG_*
|
|
// let a small task's stack silently absorb that cost — this is what overflowed
|
|
// TelemetryTask's 4096B stack in production (see feature-catalog.md F-051).
|
|
// Instead, log() copies the formatted message into a fixed-size queue item and
|
|
// a dedicated LoggingTask (its own stack) performs the actual MQTT/SD I/O.
|
|
// Serial output is NOT deferred — it's cheap and stays synchronous so what you
|
|
// see over USB reflects the true, immediate order of events (important when
|
|
// debugging a crash).
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
static constexpr size_t LOG_QUEUE_MESSAGE_MAX = 256; // truncates longer messages; see F-051 audit
|
|
static constexpr UBaseType_t LOG_QUEUE_DEPTH = 16;
|
|
|
|
struct LogQueueItem {
|
|
LogLevel level;
|
|
char tag[24];
|
|
char levelStr[6];
|
|
char message[LOG_QUEUE_MESSAGE_MAX];
|
|
bool toMqtt;
|
|
bool toSd;
|
|
};
|
|
|
|
static QueueHandle_t _logQueue;
|
|
static TaskHandle_t _loggingTaskHandle;
|
|
static portMUX_TYPE _logQueueInitSpinlock;
|
|
|
|
// Lazily created on first deferred item — MQTT/SD callbacks are registered
|
|
// well after boot (CommunicationRouter::begin()), so there's nothing to
|
|
// drain before then.
|
|
static void ensureLoggingTaskStarted();
|
|
static void loggingTask(void* parameter);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// MQTT RATE LIMITING
|
|
// Per-subsystem token bucket. Protects the broker/airtime from a chatty or
|
|
// misconfigured subsystem (e.g. a per-subsystem override left at VERBOSE).
|
|
// Drops are counted, not silently discarded — a summary line is emitted the
|
|
// next time that subsystem is allowed to publish again.
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
struct MqttRateState {
|
|
uint8_t tokens;
|
|
uint32_t lastRefillMs;
|
|
uint32_t droppedSinceLastPublish;
|
|
};
|
|
static std::map<String, MqttRateState> _mqttRateStates;
|
|
static constexpr uint8_t MQTT_RATE_BURST = 10; // max messages in a burst
|
|
static constexpr uint32_t MQTT_RATE_REFILL_MS = 1000; // 1 token regained per second
|
|
static bool allowMqttPublish(const char* tag);
|
|
};
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
// MACROS
|
|
// Each .cpp file defines: #define TAG "SubsystemName"
|
|
// Then uses: LOG_INFO(TAG, "message %d", value)
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
#define LOG_ERROR(tag, ...) Logging::error(tag, __VA_ARGS__)
|
|
#define LOG_WARNING(tag, ...) Logging::warning(tag, __VA_ARGS__)
|
|
#define LOG_INFO(tag, ...) Logging::info(tag, __VA_ARGS__)
|
|
#define LOG_DEBUG(tag, ...) Logging::debug(tag, __VA_ARGS__)
|
|
#define LOG_VERBOSE(tag, ...) Logging::verbose(tag, __VA_ARGS__)
|
|
|
|
#endif
|