Consolidate all writes to the log stream in LoggerTask

This avoids some thread-safety issues when switching log modes or reaching the log size limit.
This commit is contained in:
Cameron Gutman 2025-10-25 00:33:02 -05:00
commit 4d303cebee

View file

@ -90,6 +90,11 @@ public:
void run() override void run() override
{ {
// QTextStream is not thread-safe, so we must lock. This will generally
// only contend in synchronous logging mode or during a transition
// between synchronous and asynchronous. Asynchronous won't contend in
// the common case because we only have a single logging thread.
QMutexLocker locker(&s_SyncLoggerMutex);
s_LoggerStream << m_Msg; s_LoggerStream << m_Msg;
s_LoggerStream.flush(); s_LoggerStream.flush();
} }
@ -122,15 +127,8 @@ void logToLoggerStream(QString& message)
return; return;
} }
else if (oldLogSize >= k_MaxLogSizeBytes - message.size()) { else if (oldLogSize >= k_MaxLogSizeBytes - message.size()) {
s_LoggerThread.waitForDone(); // Write one final message
s_LoggerStream << "Log size limit reached!"; message = "Log size limit reached!";
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
s_LoggerStream << Qt::endl;
#else
s_LoggerStream << endl;
#endif
s_LoggerStream.flush();
return;
} }
#endif #endif
@ -139,10 +137,8 @@ void logToLoggerStream(QString& message)
s_LoggerThread.start(new LoggerTask(message)); s_LoggerThread.start(new LoggerTask(message));
} }
else { else {
// QTextStream is not thread-safe, so we must lock // Log the message immediately
QMutexLocker locker(&s_SyncLoggerMutex); LoggerTask(message).run();
s_LoggerStream << message;
s_LoggerStream.flush();
} }
} }