#pragma once #include #include #include #include #include #include #include #include #include static inline void rotateLog(const std::filesystem::path& logFileName, int numRotatingLogs) { const auto generateRotateNames = [&]() { std::vector rotateFileNames = {QString().fromStdString(logFileName.string())}; for(size_t i = 1; i < numRotatingLogs; ++i) { auto rotateName = logFileName.stem(); rotateName += std::string(".") + std::to_string(i); rotateName += logFileName.extension(); rotateFileNames.push_back(QString().fromStdString(rotateName.string())); } return rotateFileNames; }; const auto rotateFileNames = generateRotateNames(); for(auto i = static_cast(rotateFileNames.size()) - 2; i >= 0; --i) { QFile file(rotateFileNames[i]); QFile newFile(rotateFileNames[i + 1]); if(file.exists()) { newFile.remove(); file.rename(rotateFileNames[i + 1]); } } } void logToFile(QtMsgType msgType, [[maybe_unused]] const QMessageLogContext& msgContext, const QString& msg) { constexpr auto MAX_LOG_FILE_SIZE = 4 /*MiB*/ * 1024 * 1024; constexpr auto NUM_ROTATING_LOGS = 4; const auto logFileName = std::filesystem::path{"AdaptiveBrightness.log"}; const auto dateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"); QString formattedMsg = QString("[%1] ").arg(dateTime); switch(msgType) { case QtDebugMsg: formattedMsg += "[Debug] "; break; case QtWarningMsg: formattedMsg += "[Warning] "; break; case QtCriticalMsg: formattedMsg += "[Critical] "; break; case QtFatalMsg: formattedMsg += "[Fatal] "; break; case QtInfoMsg: formattedMsg += "[Info] "; break; } #ifdef LOG_SOURCE_LOCATION const auto msgFromFile = QString(msgContext.file); const auto msgFromLine = (msgContext.line == 0) ? QString("") : QString("%1").arg(msgContext.line); if(!msgFromFile.isEmpty() && !msgFromLine.isEmpty()) { formattedMsg += QString("[%1:%2] ").arg(msgContext.file).arg(msgContext.line); } #endif #ifdef LOG_FUNCTION_LOCATION const auto msgFromFunction = QString(msgContext.function); if(!msgFromFunction.isEmpty()) { formattedMsg += QString("[%1] ").arg(msgContext.function); } #endif formattedMsg += QString("%1").arg(msg); QFile logFile(QString().fromStdString(logFileName.string())); logFile.open(QIODevice::WriteOnly | QIODevice::Append); if(logFile.size() > MAX_LOG_FILE_SIZE) { logFile.close(); rotateLog(logFileName, NUM_ROTATING_LOGS); logFile.open(QIODevice::WriteOnly | QIODevice::Append); } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) constexpr auto qtEndl = Qt::endl; #else constexpr auto qtEndl = ::endl; #endif QTextStream textStream(&logFile); textStream << formattedMsg << qtEndl; }