Implement log rotation

This commit is contained in:
BlackMark 2020-07-09 21:54:12 +02:00
parent 7331532dfa
commit d5dad15d0a

View File

@ -1,14 +1,50 @@
#pragma once #pragma once
#include <filesystem>
#include <string>
#include <vector>
#include <cstddef>
#include <QDateTime> #include <QDateTime>
#include <QFile> #include <QFile>
#include <QMessageLogger> #include <QMessageLogger>
#include <QString> #include <QString>
#include <QTextStream> #include <QTextStream>
static inline void rotateLog(const std::filesystem::path& logFileName, int numRotatingLogs)
{
const auto generateRotateNames = [&]() {
std::vector<QString> 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<int>(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) 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"); const auto dateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
QString formattedMsg = QString("[%1] ").arg(dateTime); QString formattedMsg = QString("[%1] ").arg(dateTime);
@ -48,9 +84,15 @@ void logToFile(QtMsgType msgType, [[maybe_unused]] const QMessageLogContext& msg
formattedMsg += QString("%1").arg(msg); formattedMsg += QString("%1").arg(msg);
QFile logFile(LOG_FILE); QFile logFile(QString().fromStdString(logFileName.string()));
logFile.open(QIODevice::WriteOnly | QIODevice::Append); 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) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
constexpr auto qtEndl = Qt::endl; constexpr auto qtEndl = Qt::endl;
#else #else