refactor(tree): move the journal and the preferences out of src/ and include/
The journal and the preferences were two of the many things src/ held, so "where does this live" meant reading the file to find out. They now have a folder each — logging/ and preferences/ — with the header next to its source, the way pages/ has always been laid out. Flat #include still resolves: the folders join the include path.
This commit is contained in:
9 files changed
+37
-36
No files matched your search
@@ -0,0 +1,9 @@
|
||||
#include "app-logging.h"
|
||||
|
||||
#include <QLoggingCategory>
|
||||
|
||||
// Categories are defined once here; the header only declares them.
|
||||
Q_LOGGING_CATEGORY(pacmgrUi, "pacmgr.ui")
|
||||
Q_LOGGING_CATEGORY(pacmgrOp, "pacmgr.op")
|
||||
Q_LOGGING_CATEGORY(pacmgrPlugin, "pacmgr.plugin")
|
||||
Q_LOGGING_CATEGORY(pacmgrUpdate, "pacmgr.update")
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <QLoggingCategory>
|
||||
|
||||
// Structured log categories (P4 quality): use qCDebug/qCInfo/qCWarning with
|
||||
// these instead of scattering qDebug() so logs can be filtered per area with
|
||||
// QT_LOGGING_RULES="pacmgr.ui.debug=true" etc.
|
||||
Q_DECLARE_LOGGING_CATEGORY(pacmgrUi)
|
||||
Q_DECLARE_LOGGING_CATEGORY(pacmgrOp)
|
||||
Q_DECLARE_LOGGING_CATEGORY(pacmgrPlugin)
|
||||
Q_DECLARE_LOGGING_CATEGORY(pacmgrUpdate)
|
||||
@@ -0,0 +1,259 @@
|
||||
#include "log-manager.h"
|
||||
|
||||
#include "app-settings.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QLoggingCategory>
|
||||
#include <QStandardPaths>
|
||||
#include <QStringBuilder>
|
||||
#include <QStringList>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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<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) {
|
||||
// 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<int>(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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMutex>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
// 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.
|
||||
//
|
||||
// Two kinds of entry share the file:
|
||||
//
|
||||
// - 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, and both that directory and a size cap
|
||||
// are the user's to choose on the Settings screen: changing either takes effect
|
||||
// immediately, the existing journal being moved along (see AppSettings).
|
||||
//
|
||||
// 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);
|
||||
|
||||
// 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 journal file already contains at least one entry.
|
||||
bool hasEntries() const;
|
||||
|
||||
// Path of the journal as written on disk (useful for debugging).
|
||||
QString filePath() const;
|
||||
|
||||
// Size the journal currently takes on disk, 0 when there is none yet. The
|
||||
// Settings screen shows it next to the cap the user picked.
|
||||
qint64 currentSizeBytes() const;
|
||||
|
||||
// Path of the rotated journal, kept so the user can still read what came
|
||||
// before the last rotation.
|
||||
static QString backupFilePath();
|
||||
|
||||
// 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 journal changed on disk and a fresh copy of its content is available.
|
||||
void fileUpdated();
|
||||
|
||||
private:
|
||||
// Appends `text` verbatim, opening the file lazily. Caller does not hold the
|
||||
// lock; this method takes it.
|
||||
void write(const QString& text);
|
||||
|
||||
// Applies the current AppSettings: moves the journal to the configured
|
||||
// directory and adopts the size cap. Called once from the constructor and
|
||||
// again whenever a setting changes.
|
||||
void applySettings();
|
||||
|
||||
QString m_filePath;
|
||||
FILE* m_file = nullptr;
|
||||
mutable QMutex m_mutex;
|
||||
};
|
||||
Reference in new issue
Block a user