XPlor/libs/core/logmanager.cpp

88 lines
2.1 KiB
C++
Raw Normal View History

2025-03-01 20:38:52 -05:00
#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();
}
2025-03-01 20:38:52 -05:00
void LogManager::addEntry(const QString &entry) {
2025-04-04 20:41:23 -04:00
qDebug() << entry;
emitOrBuffer(entry);
writeToFile(entry);
2025-03-01 20:38:52 -05:00
}
void LogManager::addError(const QString &error) {
QString errorEntry = QString("ERROR: " + error);
emitOrBuffer(errorEntry);
writeToFile(errorEntry);
2025-03-01 20:38:52 -05:00
}
void LogManager::addLine() {
emitOrBuffer("");
writeToFile("");
2025-03-01 20:38:52 -05:00
}
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();
}