69 lines
2.5 KiB
C++
69 lines
2.5 KiB
C++
#include "logger.h"
|
|
#include "settings.h"
|
|
#include <QFileInfo>
|
|
#include <sys/stat.h>
|
|
|
|
QString Logging::fileName = "../logs/EventConfigurator.log";
|
|
qint64 Logging::maxFileSize = 1024 *1024 * 10;
|
|
int Logging::maxBackupFiles = 5;
|
|
bool Logging::outputToConsole = false;
|
|
bool Logging::outputToFile = true;
|
|
QString Logging::messagePattern = "[%{time yyyyMMdd h:mm:ss.zzz ttt} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}";
|
|
|
|
QtMessageHandler Logging::originalHandler = nullptr;
|
|
|
|
void Logging::setupLogging()
|
|
{
|
|
fileName = Settings::instance().value("Log", "logFile").toString();
|
|
messagePattern = Settings::instance().value("Log", "pattern").toString();
|
|
maxFileSize = Settings::instance().value("Log", "maxSize").toLongLong();
|
|
maxBackupFiles = Settings::instance().value("Log", "backups").toInt();
|
|
outputToConsole = Settings::instance().value("Log", "consoleOutput").toBool();
|
|
outputToFile = Settings::instance().value("Log", "fileOutput").toBool();
|
|
|
|
qSetMessagePattern(messagePattern);
|
|
originalHandler = qInstallMessageHandler(Logging::logMessageHandler);
|
|
}
|
|
|
|
void Logging::logMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
|
|
{
|
|
QString message = qFormatLogMessage(type, context, msg);
|
|
|
|
if (outputToFile) {
|
|
static FILE *f = fopen(Logging::fileName.toLocal8Bit().constData(), "a");
|
|
if (f) {
|
|
fprintf(f, "%s\n", qPrintable(message));
|
|
fflush(f);
|
|
}
|
|
else {
|
|
f = fopen(Logging::fileName.toLocal8Bit().constData(), "a");
|
|
if (f) {
|
|
fprintf(f, "%s\n", qPrintable(message));
|
|
fflush(f);
|
|
}
|
|
}
|
|
|
|
struct stat st;
|
|
stat(Logging::fileName.toLocal8Bit().constData(), &st);
|
|
auto fileSize = st.st_size;
|
|
if(fileSize > Logging::maxFileSize) {
|
|
if (f) {
|
|
fclose(f);
|
|
f = nullptr;
|
|
}
|
|
rollLogFiles();
|
|
}
|
|
}
|
|
|
|
if (originalHandler && outputToConsole)
|
|
(*originalHandler)(type, context, msg);
|
|
}
|
|
|
|
void Logging::rollLogFiles()
|
|
{
|
|
QFile::remove(QString("%1.%2").arg(Logging::fileName).arg(Logging::maxBackupFiles));
|
|
for(int i = Logging::maxBackupFiles - 1; i > 0; i--)
|
|
QFile::rename(QString("%1.%2").arg(Logging::fileName).arg(i), QString("%1.%2").arg(Logging::fileName).arg(i + 1));
|
|
QFile::rename(Logging::fileName, QString("%1.1").arg(Logging::fileName));
|
|
}
|