From 8670c02eb3b83a3be27b9dd582cbc565b7fbdf35 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Sun, 27 Sep 2026 18:18:51 +0200 Subject: [PATCH] feat(logs): record every operation and event in an application journal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app kept no durable trace of what it ran: LogManager existed but was never instantiated, so only a handful of console-only qCInfo calls survived a session. Wire it up as a process-wide journal that captures each command's raw output next to UI, search, plugin and update events, and funnel every Qt log message into it, so a failure can still be diagnosed after the fact. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- CMakeLists.txt | 4 +- include/app-core.h | 3 + include/log-manager.h | 108 ++++++++++++++---------- src/app-core.cpp | 147 ++++++++++++++++++++++++++++---- src/log-manager.cpp | 184 +++++++++++++++++++++++++++-------------- src/main.cpp | 18 +++- src/pacman-manager.cpp | 1 - 7 files changed, 335 insertions(+), 130 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1509c51..d55da77 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -185,9 +185,9 @@ add_executable(app-core-test tests/app-core.test.cpp src/app-core.cpp src/workers.cpp src/pacman-manager.cpp src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp src/plugin-shop.cpp - src/app-logging.cpp + src/app-logging.cpp src/log-manager.cpp include/app-core.h include/workers.h include/update-manager.h - include/plugin-shop.h) + include/plugin-shop.h include/log-manager.h) target_include_directories(app-core-test PRIVATE include) target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network) target_compile_definitions(app-core-test PRIVATE diff --git a/include/app-core.h b/include/app-core.h index a75edd6..85d9db5 100644 --- a/include/app-core.h +++ b/include/app-core.h @@ -121,6 +121,9 @@ public: // Full content of /var/log/pacman.log; `error` is filled when it cannot be // read (file missing, no permission). QString readPackageLog(QString* error = nullptr) const; + // Full content of the application's own journal (every operation and event, + // including the raw output of the commands that ran). + QString readAppLog(QString* error = nullptr) const; // Extra pacman information for the details panel (-Qi / -Si), cached per // package so selecting rows repeatedly does not re-spawn pacman. QString packageDetails(const PackageInfo& package); diff --git a/include/log-manager.h b/include/log-manager.h index b026c0a..8978a8b 100644 --- a/include/log-manager.h +++ b/include/log-manager.h @@ -1,71 +1,89 @@ #pragma once +#include #include #include -// Writes a complete, human readable (tty style) log of every package -// operation: each command that runs, the raw output it produced, the outcome -// when it finishes, and the time it happened. Everything is appended to one -// plain text file so the Logs screen can display it and the user can grep it -// like any command history: +#include + +// The application's single, always-on journal: everything the app does ends up +// in one plain-text file that the Logs screen displays and the user can grep +// like a terminal history. // -// [2026-09-23 14:22:03] pacman install linux-headers -// [2026-09-23 14:22:03] ────────────────────────────────────────────── -// [2026-09-23 14:22:04] :: Synchronizing package databases... -// [2026-09-23 14:22:05] :: Received timestamp for linux-headers ... -// ... -// [2026-09-23 14:22:10] ==> Aucun paquet à installer, vérification... -// [2026-09-23 14:22:10] Installation de linux-headers... [terminé] +// Two kinds of entry share the file: // -// The file lives next to the application in a directory that exists on every -// desktop session (XDG_CONFIG_HOME or the user home), so it is never lost when -// the sandbox is rebuilt. +// - a *command* records what a provider is about to run and then every raw +// line it prints, exactly what running the tool by hand would show: +// +// [2026-09-23 14:22:03] ── pacman · install ────────────────────────── +// [2026-09-23 14:22:03] $ install linux-headers +// [2026-09-23 14:22:04] :: Synchronizing package databases... +// [2026-09-23 14:22:05] :: Received timestamp for linux-headers ... +// ... +// [2026-09-23 14:22:10] ⟶ terminé +// +// - an *event* is a one-line note about something that is not a shelled +// command: navigation, a search, a plugin toggle, a network fetch, a refused +// request... +// +// [2026-09-23 14:22:02] [ui] navigation → recherche +// [2026-09-23 14:22:03] [recherche] "firefox" → 12 résultat(s) +// +// Every Qt log message (qCDebug/qCInfo/qCWarning/qCCritical) is funnelled into +// the same journal by installQtMessageHandler(), so the categories already used +// across the code base feed it without extra plumbing. +// +// The file lives in the user's own data tree (XDG_CONFIG_HOME / home) so it is +// never lost when a sandbox is rebuilt. All methods are safe to call from any +// thread. class LogManager : public QObject { Q_OBJECT public: + // Process-wide journal, created on first use (thread-safe). + static LogManager& instance(); + explicit LogManager(QObject* parent = nullptr); - // Full, plain text content of the log file (empty when nothing was - // written yet). `error` is filled when the file cannot be read at all. + // Records a one-line event. `category` is the short tag shown in brackets + // (e.g. "ui", "recherche", "plugin", "erreur"). + void logEvent(const QString& category, const QString& message); + + // Opens a command block: the provider(s) and action, plus a human-readable + // form of the command about to run (may be empty). + void beginCommand(const QString& provider, const QString& action, + const QString& command = QString()); + + // Appends one raw output line of the running command. + void appendOutput(const QString& line); + + // Closes the current command block with its outcome. `error` carries the + // failure detail when the command failed. + void endCommand(bool success, const QString& error = QString()); + + // Full, plain text content of the journal (empty when nothing was written + // yet). `error` is filled when the file cannot be read at all. QString readFile(QString* error = nullptr) const; - // True when the log file already contains at least one entry. + // True when the journal file already contains at least one entry. bool hasEntries() const; - // Path of the log file as written on disk (useful for debugging). + // Path of the journal as written on disk (useful for debugging). QString filePath() const; + // Routes every Qt log message into the journal. Call once, after the + // QApplication exists. Safe to call more than once. + static void installQtMessageHandler(); + signals: - // The log file was rewritten (e.g. after an operation finished) and a new - // copy of its content is available. + // The journal changed on disk and a fresh copy of its content is available. void fileUpdated(); private: - // Starts a new operation in the log. `manager`, `action` and `command` are - // the fields the user cares about; the rest is filled in by the caller. - void beginOperation(const QString& manager, const QString& action, - const QString& command); - - // Appends one line of output from the running command to the log. - void appendLine(const QString& line); - - // Closes the current operation with the final outcome. `success` tells - // whether the command exited normally, `error` carries the last output - // lines when it failed (so a clean failure is still a full log). - void endOperation(bool success, const QString& error = QString()); - - // Opens (or creates) the log file for appending and returns true on - // success. `error` is filled with the reason when opening failed. - bool openFile(QString* error = nullptr); - - // Closes the file if it was left open by the previous operation. - void closeFile(); - - // Appends a header line the way a terminal would: one line of "=" long - // enough to sit between the section title and the content. - static void appendSectionHeader(QString& text, int width = 46); + // Appends `text` verbatim, opening the file lazily. Caller does not hold the + // lock; this method takes it. + void write(const QString& text); QString m_filePath; - mutable QString m_lastError; FILE* m_file = nullptr; + mutable QMutex m_mutex; }; diff --git a/src/app-core.cpp b/src/app-core.cpp index 4bb73fb..b38ff4c 100644 --- a/src/app-core.cpp +++ b/src/app-core.cpp @@ -12,6 +12,7 @@ #include #include "app-logging.h" +#include "log-manager.h" #include "plugin-shop.h" #include "workers.h" @@ -67,6 +68,10 @@ AppCore::StartResult accepted() { AppCore::StartResult refused(const QString& error, bool needsPassword = false, bool locked = false) { + // Every refusal is part of "what happened": the journal records it even when + // the reason is routine (missing password, locked database, busy core). + LogManager::instance().logEvent(QStringLiteral("refus"), error); + AppCore::StartResult result; result.error = error; result.needsPassword = needsPassword; @@ -74,6 +79,16 @@ AppCore::StartResult refused(const QString& error, bool needsPassword = false, return result; } +// "pacman + flatpak", for the journal header of an operation. +QString providerLabel(const std::vector& providers) { + QStringList names; + for (IPackageManager* pm : providers) { + if (pm) names << QString::fromStdString(pm->getName()); + } + return names.isEmpty() ? QStringLiteral("aucun") + : names.join(QStringLiteral(" + ")); +} + } // namespace AppCore::AppCore(QObject* parent) : QObject(parent) { @@ -126,6 +141,13 @@ AppCore::AppCore(QObject* parent) : QObject(parent) { qCInfo(pacmgrOp) << "core ready," << static_cast(availableProviders().size()) << "provider(s) available"; + + LogManager::instance().logEvent( + QStringLiteral("app"), + QStringLiteral("PacManager %1 démarré — %2 gestionnaire(s) : %3") + .arg(version()) + .arg(static_cast(availableProviders().size())) + .arg(providerLabel(availableProviders()))); } AppCore::~AppCore() { @@ -227,8 +249,14 @@ void AppCore::setCredentialMode(CredentialMode mode) { if (mode == CredentialMode::EachTime) { // Each operation must re-authenticate: never keep the password around. clearSudoPassword(); + LogManager::instance().logEvent( + QStringLiteral("config"), + QStringLiteral("identifiants sudo demandés à chaque opération")); emit statusMessage(QStringLiteral("Identifiants demandés à chaque opération.")); } else { + LogManager::instance().logEvent( + QStringLiteral("config"), + QStringLiteral("identifiants sudo demandés une fois par session")); emit statusMessage(QStringLiteral("Identifiants enregistrés pour la session.")); } } @@ -305,17 +333,20 @@ AppCore::StartResult AppCore::startList(ListMode mode) { return accepted(); } + QString listLabel; switch (mode) { case ListMode::Installed: - emit statusMessage(QStringLiteral("Chargement des paquets installés...")); + listLabel = QStringLiteral("Chargement des paquets installés..."); break; case ListMode::Updates: - emit statusMessage(QStringLiteral("Recherche des mises à jour...")); + listLabel = QStringLiteral("Recherche des mises à jour..."); break; case ListMode::Cleanup: - emit statusMessage(QStringLiteral("Analyse des paquets inutilisés et legacy...")); + listLabel = QStringLiteral("Analyse des paquets inutilisés et legacy..."); break; } + LogManager::instance().logEvent(QStringLiteral("liste"), listLabel); + emit statusMessage(listLabel); auto* worker = new ListWorker(availableProviders(), mode == ListMode::Installed ? ListWorker::Installed @@ -327,26 +358,30 @@ AppCore::StartResult AppCore::startList(ListMode mode) { [this, mode](std::vector results) { m_list = nullptr; + QString done; if (mode == ListMode::Installed) { m_installedPackages = results; - emit statusMessage(QStringLiteral("%1 paquet(s) installé(s)") - .arg(results.size())); + done = QStringLiteral("%1 paquet(s) installé(s)") + .arg(results.size()); } else if (mode == ListMode::Updates) { m_updatePackages = results; - emit statusMessage(QStringLiteral("%1 mise(s) à jour disponible(s)") - .arg(results.size())); + done = QStringLiteral("%1 mise(s) à jour disponible(s)") + .arg(results.size()); } else { m_cleanupCandidates = results; int orphans = 0; for (const auto& pkg : results) { if (pkg.orphan) ++orphans; } - emit statusMessage(QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy " - "détecté(s)") - .arg(orphans) - .arg(static_cast(results.size()) - orphans)); + done = QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy " + "détecté(s)") + .arg(orphans) + .arg(static_cast(results.size()) - orphans); } + LogManager::instance().logEvent(QStringLiteral("liste"), done); + emit statusMessage(done); + emit listFinished(mode, results); if (!m_queuedLists.isEmpty()) { @@ -383,6 +418,9 @@ AppCore::StartResult AppCore::startSearch(const QString& query) { return refused(QStringLiteral("Aucun gestionnaire de paquets disponible sur ce système.")); } + LogManager::instance().logEvent( + QStringLiteral("recherche"), + QStringLiteral("\"%1\" via %2").arg(query.trimmed(), providerLabel(providers))); emit statusMessage(QStringLiteral("Recherche en cours...")); auto* worker = new SearchWorker(providers, query.trimmed().toStdString()); @@ -392,7 +430,10 @@ AppCore::StartResult AppCore::startSearch(const QString& query) { connect(worker, &SearchWorker::finished, this, [this](std::vector results) { m_search = nullptr; - emit statusMessage(QStringLiteral("%1 paquet(s) trouvé(s)").arg(results.size())); + const QString done = QStringLiteral("%1 paquet(s) trouvé(s)") + .arg(results.size()); + LogManager::instance().logEvent(QStringLiteral("recherche"), done); + emit statusMessage(done); emit searchFinished(results); }); disposeWorker(worker); @@ -471,12 +512,22 @@ AppCore::StartResult AppCore::releaseDatabaseLock() { setBusy(true); emit statusMessage(QStringLiteral("Libération de la base de données pacman...")); + LogManager::instance().beginCommand( + QStringLiteral("pacman"), QStringLiteral("release-lock"), + QString::fromStdString(PacmanManager::describeLockHolder(holder))); + auto* worker = new InstallWorker(m_pacman, holder); connect(worker, &InstallWorker::progress, this, - [this](const QString& message) { emit statusMessage(message); }); + [this](const QString& message) { + if (!message.isEmpty()) LogManager::instance().appendOutput(message); + emit statusMessage(message); + }); connect(worker, &InstallWorker::finished, this, [this](bool released) { setBusy(false); - if (!m_pacman) return; + if (!m_pacman) { + LogManager::instance().endCommand(released); + return; + } if (!released) { emit statusMessage(QStringLiteral("Base pacman toujours verrouillée")); // The core is only asked to free the lock when it is actually held: @@ -484,11 +535,14 @@ AppCore::StartResult AppCore::releaseDatabaseLock() { // Reported as a plain failure (not as another lock): the view // already went through its lock dialog once, offering it again // would loop. + LogManager::instance().endCommand( + false, QString::fromStdString(m_pacman->lastError())); emit actionFinished(QStringLiteral("release-lock"), QString(), false, QString::fromStdString(m_pacman->lastError()), /*locked=*/false); return; } + LogManager::instance().endCommand(true); emit statusMessage(QStringLiteral("Base libérée, reprise de l'opération...")); // Deferred so the status message paints before the replayed action // starts streaming its own progress. @@ -610,6 +664,9 @@ AppCore::StartResult AppCore::startRequest(const Request& request) { if (bulk) { m_removalSuccess = true; + LogManager::instance().beginCommand( + providerLabel(providers), QStringLiteral("cleanup"), + request.description); startNextRemovalGroup(); return accepted(); } @@ -657,8 +714,21 @@ AppCore::StartResult AppCore::startAction(InstallWorker* worker, const Request& qCInfo(pacmgrOp) << request.action << QString::fromStdString(request.package.name); + // Journal header: what is about to run, so the raw output that follows reads + // like a hand-run command. + const QString target = QString::fromStdString(request.package.name); + LogManager::instance().beginCommand( + providerLabel(providers), request.action, + target.isEmpty() ? QString() + : QStringLiteral("%1 %2").arg(request.action, target)); + connect(worker, &InstallWorker::progress, this, - [this](const QString& message) { emit actionProgress(message, -1); }); + [this](const QString& message) { + // Every non-empty line is the provider's own output: it is exactly + // what running the tool by hand would have printed. + if (!message.isEmpty()) LogManager::instance().appendOutput(message); + emit actionProgress(message, -1); + }); connect(worker, &InstallWorker::progressValue, this, [this](int percent) { emit actionProgress(QString(), percent); }); connect(worker, &InstallWorker::finished, this, @@ -723,6 +793,7 @@ void AppCore::finishAction(const Request& request, emit pluginsChanged(); } + LogManager::instance().endCommand(success, error); emit actionFinished(action, name, success, error, locked); } @@ -795,6 +866,7 @@ void AppCore::clearCredentialsAfterUse() { void AppCore::startNextRemovalGroup() { if (m_pendingRemovals.empty()) { + LogManager::instance().endCommand(m_removalSuccess); m_removalSuccess = true; setBusy(false); clearCredentialsAfterUse(); @@ -812,14 +884,20 @@ void AppCore::startNextRemovalGroup() { IPackageManager* provider = job.first; const std::vector packages = job.second; - emit actionProgress(QStringLiteral("Suppression de %1 paquet(s)...") - .arg(packages.size()), -1); + const QString groupLabel = QStringLiteral("Suppression de %1 paquet(s) via %2...") + .arg(packages.size()) + .arg(QString::fromStdString(provider->getName())); + LogManager::instance().appendOutput(groupLabel); + emit actionProgress(groupLabel, -1); auto* worker = new InstallWorker(provider, InstallWorker::Op::RemovePackages, packages); m_action = worker; connect(worker, &InstallWorker::progress, this, - [this](const QString& message) { emit actionProgress(message, -1); }); + [this](const QString& message) { + if (!message.isEmpty()) LogManager::instance().appendOutput(message); + emit actionProgress(message, -1); + }); connect(worker, &InstallWorker::progressValue, this, [this](int percent) { emit actionProgress(QString(), percent); }); connect(worker, &InstallWorker::finished, this, @@ -856,6 +934,7 @@ void AppCore::startNextRemovalGroup() { const QString error = QString::fromStdString(provider->lastError()); const bool locked = (m_pacman && m_pacman->lastErrorWasLock()) || PacmanManager::dbLocked(provider->lastError()); + LogManager::instance().endCommand(false, error); emit statusMessage(QStringLiteral("Échec du nettoyage")); emit actionFinished(QStringLiteral("cleanup"), m_cleanupRemovalDescription, false, error, locked); @@ -893,12 +972,19 @@ void AppCore::cancelPendingRequest() { // --------------------------------------------------------------------------- void AppCore::setPluginEnabled(const std::string& pluginId, bool enabled) { + LogManager::instance().logEvent( + QStringLiteral("plugin"), + QStringLiteral("%1 %2") + .arg(QString::fromStdString(pluginId), + enabled ? QStringLiteral("activé") : QStringLiteral("désactivé"))); m_plugins->setEnabled(pluginId, enabled); refreshProviderCache(); emit pluginsChanged(); } void AppCore::reloadPlugins() { + LogManager::instance().logEvent(QStringLiteral("plugin"), + QStringLiteral("registre rechargé")); m_plugins->reload(); refreshProviderCache(); emit pluginsChanged(); @@ -906,20 +992,30 @@ void AppCore::reloadPlugins() { } void AppCore::loadPluginCatalog() { + LogManager::instance().logEvent(QStringLiteral("plugin"), + QStringLiteral("chargement du catalogue")); emit statusMessage(QStringLiteral("Chargement du catalogue de plugins...")); m_shop->refresh(); } void AppCore::installShopPlugin(const QString& id) { + LogManager::instance().logEvent( + QStringLiteral("plugin"), + QStringLiteral("installation depuis la boutique : %1").arg(id)); emit statusMessage(QStringLiteral("Téléchargement du plugin %1...").arg(id)); m_shop->install(id); } void AppCore::removeShopPlugin(const QString& id) { + LogManager::instance().logEvent( + QStringLiteral("plugin"), + QStringLiteral("suppression depuis la boutique : %1").arg(id)); m_shop->remove(id); } void AppCore::clearHistory() { + LogManager::instance().logEvent(QStringLiteral("historique"), + QStringLiteral("effacé")); m_history->clear(); emit historyChanged(); emit statusMessage(QStringLiteral("Historique effacé")); @@ -933,6 +1029,7 @@ QString AppCore::readPackageLog(QString* error) const { "Vérifiez que le fichier existe et que vous avez les " "droits de lecture.") .arg(QString::fromUtf8(kPacmanLogPath)); + LogManager::instance().logEvent(QStringLiteral("erreur"), *error); } return QString(); } @@ -940,6 +1037,10 @@ QString AppCore::readPackageLog(QString* error) const { return QString::fromUtf8(logFile.readAll()); } +QString AppCore::readAppLog(QString* error) const { + return LogManager::instance().readFile(error); +} + QString AppCore::packageDetails(const PackageInfo& pkg) { if (!m_pacman || !m_pacman->isAvailable()) return QString(); @@ -953,6 +1054,12 @@ QString AppCore::packageDetails(const PackageInfo& pkg) { const auto cached = m_detailsCache.constFind(key); if (cached != m_detailsCache.constEnd()) return cached.value(); + LogManager::instance().logEvent( + QStringLiteral("détails"), + QStringLiteral("interrogation de %1 (%2)") + .arg(QString::fromStdString(pkg.name), + QString::fromStdString(pkg.provider))); + const bool isPacmanPkg = pkg.provider == "pacman" || pkg.provider.empty(); const std::string queryInstalled = pkg.provider == "aur" ? "yay -Qi " : "pacman -Qi "; const std::string querySync = pkg.provider == "aur" ? "yay -Si " : "pacman -Si "; @@ -999,6 +1106,8 @@ bool AppCore::shouldCheckForAppUpdate() const { } void AppCore::checkForAppUpdate() { + LogManager::instance().logEvent(QStringLiteral("maj-app"), + QStringLiteral("vérification de version")); emit statusMessage(QStringLiteral("Vérification des mises à jour...")); m_update->checkForUpdates(); } @@ -1035,6 +1144,8 @@ bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) { return false; } if (error) error->clear(); + LogManager::instance().logEvent(QStringLiteral("maj-app"), + QStringLiteral("mise à jour appliquée")); m_update->performSelfUpdate(sudoPassword); return true; } diff --git a/src/log-manager.cpp b/src/log-manager.cpp index 90bd45a..de04557 100644 --- a/src/log-manager.cpp +++ b/src/log-manager.cpp @@ -3,8 +3,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -12,9 +14,9 @@ namespace { -// Where a plain text history of what the app did lives on any desktop -// session, inside the user's own data tree (so a Flatpak-sandboxed build -// still finds it in ~/.local/share). +// Where the plain text history of what the app did lives on any desktop +// session, inside the user's own data tree (so a Flatpak-sandboxed build still +// finds it in ~/.local/share). QString logDirectory() { const QString dir = QStandardPaths::writableLocation( QStandardPaths::AppConfigLocation); @@ -25,8 +27,19 @@ QString logDirectory() { return QDir::homePath() + QStringLiteral("/.config/PacManager"); } +QString currentTimestamp() { + return QDateTime::currentDateTime().toString( + QStringLiteral("yyyy-MM-dd hh:mm:ss")); +} + } // 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) { m_filePath = logDirectory() + QStringLiteral("/") + QStringLiteral("operations.log"); } @@ -35,84 +48,100 @@ QString LogManager::filePath() const { return m_filePath; } -bool LogManager::openFile(QString* error) { - // Append mode: a long session keeps growing, and the file is never - // truncated while the app runs. - m_file = std::fopen(QFile::encodeName(m_filePath).constData(), "a"); +void LogManager::write(const QString& text) { + QMutexLocker lock(&m_mutex); + + // 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) { - if (error) { - *error = QString::fromLocal8Bit( - strerror(errno)) + QStringLiteral(" : ") - + QFile::decodeName(QFile::encodeName(m_filePath)); - } - return false; + m_file = std::fopen(QFile::encodeName(m_filePath).constData(), "a"); + if (!m_file) return; } - if (error) error->clear(); - return true; + + const QByteArray bytes = text.toUtf8(); + 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::closeFile() { - if (m_file) { - std::fclose(m_file); - m_file = nullptr; - } -} +void LogManager::logEvent(const QString& category, const QString& message) { + if (message.isEmpty()) return; -void LogManager::beginOperation(const QString& manager, const QString& action, - const QString& command) { - closeFile(); - if (!openFile()) 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()); - const QString stamp = QDateTime::currentDateTime().toString( - QStringLiteral("yyyy-MM-dd hh:mm:ss")); - const QString line = QStringLiteral("[%1] %2 %3 %4\n") - .arg(stamp) - .arg(manager) - .arg(action) - .arg(command); - std::fputs(QFile::encodeName(line).constData(), m_file); -} - -void LogManager::appendLine(const QString& line) { - if (!m_file) return; - const QString out = QStringLiteral(" %1\n").arg(line); - std::fputs(QFile::encodeName(out).constData(), m_file); -} - -void LogManager::endOperation(bool success, const QString& error) { - const QString stamp = QDateTime::currentDateTime().toString( - QStringLiteral("yyyy-MM-dd hh:mm:ss")); - const QString outcome = - success ? QStringLiteral(" [terminé]") : QStringLiteral(" [erreur]:"); - QString out = QStringLiteral("[%1] %2%3\n") - .arg(stamp) - .arg(QString()) - .arg(outcome); - if (!error.isEmpty()) { - out += error; - out += '\n'; - } - std::fputs(QFile::encodeName(out).constData(), m_file); - closeFile(); + write(QStringLiteral("[%1] [%2] %3\n").arg(currentTimestamp(), category, flat)); emit fileUpdated(); } -void LogManager::appendSectionHeader(QString& text, int width) { - text += QStringLiteral("\n%1\n").arg(QStringLiteral("=").repeated(width)); +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) { + QString text = QStringLiteral("[%1] %2\n") + .arg(currentTimestamp(), + success ? QStringLiteral("⟶ terminé") + : QStringLiteral("⟶ é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 { - if (!QFile::exists(m_filePath)) return QString(); + 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); + 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 log into memory + + // Read the file in chunks to avoid loading a very large journal into memory // at once; the file grows with session usage. - const int bufferSize = 8192; + constexpr int bufferSize = 8192; QByteArray chunk; chunk.resize(bufferSize); QString result; @@ -128,3 +157,32 @@ QString LogManager::readFile(QString* error) const { 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 = QStringLiteral("avertissement"); break; + case QtCriticalMsg: level = QStringLiteral("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(); + }); +} diff --git a/src/main.cpp b/src/main.cpp index 8faafda..aff137a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,7 @@ #include +#include + +#include "log-manager.h" #include "main-window.h" #include "update-manager.h" @@ -8,11 +11,24 @@ int main(int argc, char* argv[]) { app.setApplicationVersion(UpdateManager::currentVersion()); app.setOrganizationName("Freebuff"); + // Every log category the app uses is enabled (qCDebug included) and funnelled + // into the journal, so the Logs screen shows the same detail as a debug run + // without the user having to set QT_LOGGING_RULES. + QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true")); + LogManager::installQtMessageHandler(); + LogManager::instance().logEvent( + QStringLiteral("app"), + QStringLiteral("session démarrée (v%1)").arg(UpdateManager::currentVersion())); + MainWindow window; window.setWindowTitle("PacManager - Gestionnaire de Paquets"); window.resize(1200, 760); window.setMinimumSize(960, 600); window.show(); - return app.exec(); + const int code = app.exec(); + + LogManager::instance().logEvent(QStringLiteral("app"), + QStringLiteral("session terminée (code %1)").arg(code)); + return code; } diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index f4dadf8..d338457 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -1,4 +1,3 @@ -#include "log-manager.h" #include "pacman-manager.h" #include "progress-tracker.h"