- Add log-to-file functionality with configurable path - Buffer log entries before listeners connect to prevent lost messages - Add flush mechanism for buffered entries - Improve utils.h with additional helper functions Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
88 lines
2.1 KiB
C++
88 lines
2.1 KiB
C++
#include "logmanager.h"
|
|
#include <QDebug>
|
|
#include <QCoreApplication>
|
|
#include <QDateTime>
|
|
#include <QTextStream>
|
|
|
|
LogManager::~LogManager()
|
|
{
|
|
if (m_logFile) {
|
|
m_logFile->close();
|
|
delete m_logFile;
|
|
}
|
|
}
|
|
|
|
void LogManager::emitOrBuffer(const QString &entry) {
|
|
if (m_hasListeners) {
|
|
emit entryAdded(entry);
|
|
} else {
|
|
m_bufferedEntries.append(entry);
|
|
}
|
|
}
|
|
|
|
void LogManager::flushBufferedEntries() {
|
|
m_hasListeners = true;
|
|
for (const QString &entry : m_bufferedEntries) {
|
|
emit entryAdded(entry);
|
|
}
|
|
m_bufferedEntries.clear();
|
|
}
|
|
|
|
void LogManager::addEntry(const QString &entry) {
|
|
qDebug() << entry;
|
|
emitOrBuffer(entry);
|
|
writeToFile(entry);
|
|
}
|
|
|
|
void LogManager::addError(const QString &error) {
|
|
QString errorEntry = QString("ERROR: " + error);
|
|
emitOrBuffer(errorEntry);
|
|
writeToFile(errorEntry);
|
|
}
|
|
|
|
void LogManager::addLine() {
|
|
emitOrBuffer("");
|
|
writeToFile("");
|
|
}
|
|
|
|
void LogManager::debug(const QString &entry) {
|
|
if (m_debugChecker && m_debugChecker()) {
|
|
addEntry(entry);
|
|
}
|
|
}
|
|
|
|
void LogManager::setDebugChecker(std::function<bool()> checker) {
|
|
m_debugChecker = std::move(checker);
|
|
}
|
|
|
|
void LogManager::setLogToFileChecker(std::function<bool()> checker) {
|
|
m_logToFileChecker = std::move(checker);
|
|
}
|
|
|
|
void LogManager::writeToFile(const QString &entry) {
|
|
// Check if log to file is enabled
|
|
if (!m_logToFileChecker || !m_logToFileChecker()) {
|
|
return;
|
|
}
|
|
|
|
// Open log file if not already open
|
|
if (!m_logFile) {
|
|
QString logPath = QCoreApplication::applicationDirPath() + "/xplor.log";
|
|
m_logFile = new QFile(logPath);
|
|
if (!m_logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
|
|
delete m_logFile;
|
|
m_logFile = nullptr;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Write timestamped entry
|
|
QTextStream stream(m_logFile);
|
|
if (entry.isEmpty()) {
|
|
stream << "\n";
|
|
} else {
|
|
stream << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] ") << entry << "\n";
|
|
}
|
|
stream.flush();
|
|
}
|