guard logger QFile access with a mutex

This fixes the following assertion failure in Qt debug builds:
```
ASSERT: "bytes <= bufferSize" in file C:\Users\qt\work\qt\qtbase\src\corelib\tools\qringbuffer.cpp, line 75
```

The message handler is called from the thread that sends the message, so
we need to make sure only one thread can access the file at a time,
since QFile is not inherently threadsafe.

Signed-off-by: Jared Van Bortel <jared@nomic.ai>
This commit is contained in:
Jared Van Bortel 2025-02-05 18:14:18 -05:00
parent 350bd0a793
commit 4e18c81107
2 changed files with 16 additions and 8 deletions

View File

@ -4,6 +4,7 @@
#include <QDebug>
#include <QGlobalStatic>
#include <QIODevice>
#include <QMutexLocker>
#include <QStandardPaths>
#include <cstdio>
@ -62,8 +63,11 @@ void Logger::messageHandler(QtMsgType type, const QMessageLogContext &, const QS
}
// Get time and date
auto timestamp = QDateTime::currentDateTime().toString();
// Write message
const std::string out = u"[%1] (%2): %3\n"_s.arg(typeString, timestamp, msg).toStdString();
// Write message
QMutexLocker locker(&logger->m_mutex);
logger->m_file.write(out.c_str());
logger->m_file.flush();
std::cerr << out;

View File

@ -2,19 +2,23 @@
#define LOGGER_H
#include <QFile>
#include <QMutex>
#include <QString>
#include <QtLogging>
class Logger
{
QFile m_file;
static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg);
class Logger {
public:
explicit Logger();
static Logger *globalInstance();
explicit Logger();
private:
static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg);
private:
QFile m_file;
QMutex m_mutex;
friend class MyLogger;
};