fix(FileManager,Logging): day-rotated SD logs + boot reset-reason reporting
SD logging was a silent no-op on fresh cards: appendLine() opened /logs/vesper.log in FILE_APPEND without ever creating the /logs directory first. FileManager now exposes appendLogLine(), which creates the directory, rotates to YYYY-MM-DD.log files, and prunes oldest files once a 512KB total budget is exceeded. LoggingHandler gains logs.list / logs.download commands (chunked, paginated) so SD logs can be pulled off a device remotely for offline-device troubleshooting. Telemetry now captures esp_reset_reason() at boot and classifies it as a fault (panic/watchdog/brownout) or an expected reset (power-on/software/deep sleep). CommunicationRouter reports it once MQTT connects: faults go to status/alerts, expected resets go to status/info (type: boot_reason). MQTTDriver gained a setOnConnectCallback hook to support this. F-045, F-046, F-048 in the feature catalog.
This commit is contained in:
@@ -320,3 +320,186 @@ bool FileManager::appendLine(const String& filePath, const String& line) {
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// DAY-ROTATED SD LOG FILE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
String FileManager::logFileNameForTimestamp(time_t timestamp) const {
|
||||
// No wall clock yet (RTC absent and NTP hasn't synced) — bucket these
|
||||
// early lines together rather than losing them.
|
||||
if (timestamp <= 0) {
|
||||
return "unset-date.log";
|
||||
}
|
||||
|
||||
struct tm timeInfo;
|
||||
gmtime_r(×tamp, &timeInfo);
|
||||
|
||||
char name[16]; // "YYYY-MM-DD.log" + null
|
||||
snprintf(name, sizeof(name), "%04d-%02d-%02d.log",
|
||||
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday);
|
||||
return String(name);
|
||||
}
|
||||
|
||||
bool FileManager::appendLogLine(const String& logDir, const String& line, time_t timestamp,
|
||||
size_t maxTotalBytes) {
|
||||
if (!ensureDirectoryExists(logDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String dirPath = logDir;
|
||||
if (!dirPath.endsWith("/")) dirPath += "/";
|
||||
String fullPath = dirPath + logFileNameForTimestamp(timestamp);
|
||||
|
||||
if (!appendLine(fullPath, line)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (maxTotalBytes > 0) {
|
||||
pruneLogDirectory(logDir, maxTotalBytes);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deletes the oldest dated .log files in logDir until the directory's total
|
||||
// size is at or under maxTotalBytes. Relies on filenames sorting
|
||||
// lexicographically oldest-first (YYYY-MM-DD.log).
|
||||
void FileManager::pruneLogDirectory(const String& logDir, size_t maxTotalBytes) {
|
||||
if (!initializeSD()) {
|
||||
return;
|
||||
}
|
||||
|
||||
File dir = SD.open(logDir.c_str());
|
||||
if (!dir || !dir.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::pair<String, size_t>> files;
|
||||
size_t totalBytes = 0;
|
||||
|
||||
File file = dir.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
String name = file.name();
|
||||
size_t size = file.size();
|
||||
files.push_back({name, size});
|
||||
totalBytes += size;
|
||||
}
|
||||
file = dir.openNextFile();
|
||||
}
|
||||
dir.close();
|
||||
|
||||
if (totalBytes <= maxTotalBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::sort(files.begin(), files.end(),
|
||||
[](const std::pair<String, size_t>& a, const std::pair<String, size_t>& b) {
|
||||
return a.first < b.first;
|
||||
});
|
||||
|
||||
String dirPath = logDir;
|
||||
if (!dirPath.endsWith("/")) dirPath += "/";
|
||||
|
||||
for (const auto& entry : files) {
|
||||
if (totalBytes <= maxTotalBytes) break;
|
||||
|
||||
// entry.first may already be a full path (SD.open on some cores
|
||||
// returns the absolute name) — normalize to dirPath + basename.
|
||||
String name = entry.first;
|
||||
int lastSlash = name.lastIndexOf('/');
|
||||
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
|
||||
|
||||
String fullPath = dirPath + name;
|
||||
if (SD.remove(fullPath.c_str())) {
|
||||
LOG_INFO(TAG, "Log rotation: removed oldest log file %s (%u bytes)", fullPath.c_str(), (unsigned)entry.second);
|
||||
totalBytes -= entry.second;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String FileManager::readLogChunkAsJson(const String& logDir, const String& fileName,
|
||||
size_t offset, size_t maxBytes) {
|
||||
// Reject path traversal / nested paths — fileName must be a bare filename
|
||||
// as returned by listLogFilesAsJson.
|
||||
if (fileName.indexOf('/') >= 0 || fileName.indexOf("..") >= 0 || fileName.isEmpty()) {
|
||||
LOG_ERROR(TAG, "readLogChunkAsJson: invalid file name: %s", fileName.c_str());
|
||||
return "{}";
|
||||
}
|
||||
|
||||
if (!initializeSD()) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
String dirPath = logDir;
|
||||
if (!dirPath.endsWith("/")) dirPath += "/";
|
||||
String fullPath = dirPath + fileName;
|
||||
|
||||
File file = SD.open(fullPath.c_str(), FILE_READ);
|
||||
if (!file) {
|
||||
LOG_ERROR(TAG, "readLogChunkAsJson: file not found: %s", fullPath.c_str());
|
||||
return "{}";
|
||||
}
|
||||
|
||||
size_t fileSize = file.size();
|
||||
if (offset > fileSize) offset = fileSize;
|
||||
file.seek(offset);
|
||||
|
||||
size_t remaining = fileSize - offset;
|
||||
size_t toRead = remaining < maxBytes ? remaining : maxBytes;
|
||||
|
||||
String chunk;
|
||||
chunk.reserve(toRead + 1);
|
||||
while (chunk.length() < toRead && file.available()) {
|
||||
chunk += (char)file.read();
|
||||
}
|
||||
file.close();
|
||||
|
||||
size_t nextOffset = offset + chunk.length();
|
||||
bool eof = nextOffset >= fileSize;
|
||||
|
||||
DynamicJsonDocument doc(chunk.length() + 256);
|
||||
doc["data"] = chunk;
|
||||
doc["next_offset"] = nextOffset;
|
||||
doc["eof"] = eof;
|
||||
|
||||
String json;
|
||||
serializeJson(doc, json);
|
||||
return json;
|
||||
}
|
||||
|
||||
String FileManager::listLogFilesAsJson(const String& logDir) {
|
||||
if (!initializeSD()) {
|
||||
LOG_ERROR(TAG, "SD initialization failed");
|
||||
return "{}";
|
||||
}
|
||||
|
||||
File dir = SD.open(logDir.c_str());
|
||||
if (!dir || !dir.isDirectory()) {
|
||||
LOG_ERROR(TAG, "Log directory not found: %s", logDir.c_str());
|
||||
return "{}";
|
||||
}
|
||||
|
||||
DynamicJsonDocument doc(2048);
|
||||
JsonArray fileList = doc.createNestedArray("files");
|
||||
|
||||
File file = dir.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
String name = file.name();
|
||||
int lastSlash = name.lastIndexOf('/');
|
||||
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
|
||||
|
||||
JsonObject entry = fileList.createNestedObject();
|
||||
entry["name"] = name;
|
||||
entry["size"] = file.size();
|
||||
}
|
||||
file = dir.openNextFile();
|
||||
}
|
||||
dir.close();
|
||||
|
||||
String json;
|
||||
serializeJson(doc, json);
|
||||
return json;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user