feat(logs): record every operation and event in an application journal

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 <noreply@codebuff.com>
This commit is contained in:
BlackAngelTV committed 2026-09-27 18:18:55 +02:00
1 parent 656e365daf
commit 8670c02eb3
7 files changed
+335 -130

No files matched your search

+129 -18
View File
@@ -12,6 +12,7 @@
#include <sstream>
#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<IPackageManager*>& 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<int>(availableProviders().size())
<< "provider(s) available";
LogManager::instance().logEvent(
QStringLiteral("app"),
QStringLiteral("PacManager %1 démarré — %2 gestionnaire(s) : %3")
.arg(version())
.arg(static_cast<int>(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<PackageInfo> 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<int>(results.size()) - orphans));
done = QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy "
"détecté(s)")
.arg(orphans)
.arg(static_cast<int>(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<PackageInfo> 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<std::string> 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;
}
+121 -63
View File
@@ -3,8 +3,10 @@
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QLoggingCategory>
#include <QStandardPaths>
#include <QStringBuilder>
#include <QStringList>
#include <cstdio>
#include <cstdlib>
@@ -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<int>(action.size()) - static_cast<int>(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();
});
}
+17 -1
View File
@@ -1,4 +1,7 @@
#include <QApplication>
#include <QLoggingCategory>
#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;
}
-1
View File
@@ -1,4 +1,3 @@
#include "log-manager.h"
#include "pacman-manager.h"
#include "progress-tracker.h"