#include "log-manager.h" #include "app-settings.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace { // The journal's file name, and the one its rotated copy gets. constexpr auto kLogFileName = "operations.log"; constexpr auto kBackupFileName = "operations.log.1"; QString currentTimestamp() { return QDateTime::currentDateTime().toString( QStringLiteral("yyyy-MM-dd hh:mm:ss")); } // Renames `path` onto `target`, replacing whatever was there. Journal rotation // and the move to a new directory both want that, and Qt refuses to overwrite // otherwise. bool replaceFile(const QString& path, const QString& target) { if (!QFile::exists(path)) return true; if (QFile::exists(target) && !QFile::remove(target)) return false; return QFile::rename(path, target); } } // namespace LogManager& LogManager::instance() { // Function-local static: created once, thread-safe since C++11. static LogManager manager; return manager; } LogManager::LogManager(QObject* parent) : QObject(parent) { // Subscribing before the first write means the journal is opened where the // user asked, not where it was asked to open. AppSettings& settings = AppSettings::instance(); connect(&settings, &AppSettings::logDirectoryChanged, this, [this](const QString&) { applySettings(); }); applySettings(); } QString LogManager::filePath() const { QMutexLocker lock(&m_mutex); return m_filePath; } QString LogManager::backupFilePath() { return AppSettings::instance().logDirectory() + QLatin1Char('/') + QLatin1String(kBackupFileName); } qint64 LogManager::currentSizeBytes() const { QMutexLocker lock(&m_mutex); return QFileInfo(m_filePath).size(); } // Puts the journal where AppSettings says, carrying the existing file along so // switching directory does not silently start an empty log. void LogManager::applySettings() { const QString directory = AppSettings::instance().logDirectory(); const QString wanted = directory + QLatin1Char('/') + QLatin1String(kLogFileName); // A directory that cannot be created is reported by the absence of the // journal on the Settings screen, not by throwing here. if (!QDir().mkpath(directory)) return; QString previous; { QMutexLocker lock(&m_mutex); if (wanted == m_filePath) return; previous = m_filePath; if (m_file) { std::fclose(m_file); m_file = nullptr; } m_filePath = wanted; } // Carried over only when the target has no journal of its own: a directory // that already has one is not overwritten. Done without the lock, which // write() takes for itself. if (!previous.isEmpty()) { replaceFile(previous, wanted); } // Where the journal opened is the one line the user may want to grep, so // it is worded like the rest of the journal. write(QStringLiteral("[%1] [config] %2\n") .arg(currentTimestamp(), QCoreApplication::translate("LogManager", "journal → %1") .arg(wanted))); } void LogManager::write(const QString& text) { QMutexLocker lock(&m_mutex); const QByteArray bytes = text.toUtf8(); // Rotation before the write, so the cap really is a ceiling. One previous // journal is kept; the one before it is dropped. const qint64 cap = AppSettings::instance().logMaxBytes(); if (cap > 0 && QFileInfo(m_filePath).size() + bytes.size() > cap) { if (m_file) { std::fclose(m_file); m_file = nullptr; } replaceFile(m_filePath, m_filePath + QLatin1String(".1")); } // Append mode, opened lazily and kept open: a long session keeps growing and // the file is never truncated while the app runs. if (!m_file) { m_file = std::fopen(QFile::encodeName(m_filePath).constData(), "a"); if (!m_file) return; } std::fputs(bytes.constData(), m_file); // Flushed line by line so the journal survives a crash: the last thing the // app did is exactly what the user wants to read after one. std::fflush(m_file); } void LogManager::logEvent(const QString& category, const QString& message) { if (message.isEmpty()) return; // A Qt log message may carry several lines; flatten them so every journal // entry stays one physical line. QString flat = message; flat.replace(QLatin1Char('\n'), QStringLiteral(" ")); flat.replace(QLatin1Char('\r'), QString()); write(QStringLiteral("[%1] [%2] %3\n").arg(currentTimestamp(), category, flat)); emit fileUpdated(); } void LogManager::beginCommand(const QString& provider, const QString& action, const QString& command) { const QString stamp = currentTimestamp(); QString text = QStringLiteral("[%1] ── %2 · %3 ") .arg(stamp, provider, action); // A rule long enough to separate two operations at a glance. int rule = 46 - static_cast(action.size()) - static_cast(provider.size()); if (rule < 3) rule = 3; text += QStringLiteral("─").repeated(rule); text += QLatin1Char('\n'); if (!command.isEmpty()) { text += QStringLiteral("[%1] $ %2\n").arg(stamp, command); } write(text); emit fileUpdated(); } void LogManager::appendOutput(const QString& line) { if (line.trimmed().isEmpty()) return; // No timestamp on output lines: this is the tool's own text, replayed as it // would appear in a terminal, and timestamps on every line would drown it. write(QStringLiteral(" %1\n").arg(line)); } void LogManager::endCommand(bool success, const QString& error) { // The journal is read in the language the user picked like the interface is, // so its two outcomes are translated; the command lines around them are the // tools' own output and stay untouched. QString text = QStringLiteral("[%1] %2\n") .arg(currentTimestamp(), success ? QCoreApplication::translate("LogManager", "⟶ terminé") : QCoreApplication::translate("LogManager", "⟶ échec")); if (!error.isEmpty()) { const QStringList lines = error.split(QLatin1Char('\n')); for (const QString& line : lines) { if (line.trimmed().isEmpty()) continue; text += QStringLiteral(" %1\n").arg(line); } } write(text); emit fileUpdated(); } QString LogManager::readFile(QString* error) const { QMutexLocker lock(&m_mutex); if (!QFile::exists(m_filePath)) { if (error) error->clear(); return QString(); } QFile file(m_filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (error) { *error = QStringLiteral("Impossible d'ouvrir %1.").arg(m_filePath); } return QString(); } if (error) error->clear(); // Read the file in chunks to avoid loading a very large journal into memory // at once; the file grows with session usage. constexpr int bufferSize = 8192; QByteArray chunk; chunk.resize(bufferSize); QString result; while (!file.atEnd()) { const qint64 read = file.read(chunk.data(), bufferSize); if (read > 0) { result += QString::fromUtf8(chunk, static_cast(read)); } } return result; } bool LogManager::hasEntries() const { return !readFile().isEmpty(); } void LogManager::installQtMessageHandler() { // Make sure the singleton is created on the calling (main) thread before any // worker emits a log message. instance(); qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& context, const QString& message) { // Keep the usual console output too, so a developer still sees the logs // in a terminal. const char* category = context.category ? context.category : "default"; std::fprintf(stderr, "[%s] %s\n", category, message.toLocal8Bit().constData()); QString level; switch (type) { case QtDebugMsg: level = QStringLiteral("debug"); break; case QtInfoMsg: level = QStringLiteral("info"); break; case QtWarningMsg: level = QCoreApplication::translate("LogManager", "avertissement"); break; case QtCriticalMsg: level = QCoreApplication::translate("LogManager", "critique"); break; case QtFatalMsg: level = QStringLiteral("fatal"); break; } LogManager::instance().logEvent( QStringLiteral("qt/%1").arg(QString::fromLatin1(category)), QStringLiteral("%1: %2").arg(level, message)); if (type == QtFatalMsg) std::abort(); }); }