diff --git a/AdaptiveBrightness/log_to_file.hpp b/AdaptiveBrightness/log_to_file.hpp index b8dd709..01abfd7 100644 --- a/AdaptiveBrightness/log_to_file.hpp +++ b/AdaptiveBrightness/log_to_file.hpp @@ -1,14 +1,50 @@ #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 LOG_FILE = "AdaptiveBrightness.log"; + 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); @@ -48,9 +84,15 @@ void logToFile(QtMsgType msgType, [[maybe_unused]] const QMessageLogContext& msg formattedMsg += QString("%1").arg(msg); - QFile logFile(LOG_FILE); + 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