1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
|
#include "logger.h"
#include <QFile>
#include <QDebug>
#include <QTimer>
#include <QDateTime>
#include <QTextStream>
#include <QStandardPaths>
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(CATEGORY_LOGGER, "LOG")
Logger::Logger(QObject *parent):
QObject(parent),
m_logDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)),
m_logFile(new QFile(this)),
m_updateTimer(new QTimer(this)),
m_stderr(stderr, QIODevice::WriteOnly),
m_fileOut(m_logFile),
m_startTime(QDateTime::currentDateTime()),
m_logLevel(Default),
m_maxLineCount(200),
m_errorCount(0)
{
m_updateTimer->setSingleShot(true);
m_updateTimer->setInterval(100);
connect(m_updateTimer, &QTimer::timeout, this, &Logger::logTextChanged);
m_logDir.mkdir(APP_NAME);
if(!m_logDir.exists(APP_NAME)) {
fallbackMessageOutput(QStringLiteral("Failed to create logs directory"));
return;
} else if(!m_logDir.cd(APP_NAME)) {
fallbackMessageOutput(QStringLiteral("Failed to access logs directory"));
return;
} else if(!removeOldFiles()) {
fallbackMessageOutput(QStringLiteral("Failed to remove old files"));
return;
}
const auto fileName = QStringLiteral("%1-%2.txt").arg(APP_NAME, m_startTime.toString(QStringLiteral("yyyyMMdd-hhmmss")));
const auto filePath = m_logDir.absoluteFilePath(fileName);
m_logFile->setFileName(filePath);
if(!m_logFile->open(QIODevice::WriteOnly)) {
fallbackMessageOutput(QStringLiteral("Failed to open log file: %1").arg(m_logFile->errorString()));
}
}
Logger *Logger::instance()
{
static auto *logger = new Logger();
return logger;
}
void Logger::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
const auto text = QStringLiteral("[%1] %2").arg(context.category, msg);
const auto criticalText = QStringLiteral("<font color=\"#ff1f00\">%1</font>");
const auto timestamp = QString::number(globalLogger->m_startTime.msecsTo(QDateTime::currentDateTime()));
// Writing everything in the file regardless of the log level
if(globalLogger->m_logFile->isOpen()) {
globalLogger->m_fileOut << timestamp << ' ' << text << Qt::endl;
}
const auto filterNonError = globalLogger->m_logLevel == ErrorsOnly && type != QtCriticalMsg;
const auto filterDebug = globalLogger->m_logLevel == Terse && type == QtDebugMsg;
if(filterNonError || filterDebug) {
return;
}
globalLogger->m_stderr << timestamp << ' ' << text << Qt::endl;
const auto filterWithoutCategory = !strcmp(context.category, "default");
const auto filterPretty = type == QtDebugMsg;
if(filterWithoutCategory || filterPretty) {
return;
}
globalLogger->append(type == QtCriticalMsg ? criticalText.arg(text) : text);
globalLogger->setErrorCount(globalLogger->errorCount() + (type == QtCriticalMsg ? 1 : 0));
}
const QUrl Logger::logsPath() const
{
return QUrl::fromLocalFile(m_logDir.absolutePath());
}
const QUrl Logger::logsFile() const
{
return QUrl::fromLocalFile(m_logFile->fileName());
}
int Logger::errorCount() const
{
return m_errorCount;
}
void Logger::setErrorCount(int count)
{
if(m_errorCount == count) {
return;
}
m_errorCount = count;
emit errorCountChanged();
}
QString Logger::logText() const
{
return m_logText.join("<br/>");
}
void Logger::setLogLevel(LogLevel level)
{
m_logLevel = level;
}
void Logger::append(const QString &line)
{
m_logText.append(line);
if(m_logText.size() > m_maxLineCount) {
m_logText.removeFirst();
}
if(!m_updateTimer->isActive()) {
m_updateTimer->start();
}
}
void Logger::fallbackMessageOutput(const QString &msg)
{
m_stderr << '[' << CATEGORY_LOGGER().categoryName() << "] " << msg << Qt::endl;
}
bool Logger::removeOldFiles()
{
constexpr auto maxFileCount = 99;
const auto files = m_logDir.entryInfoList(QDir::Files, QDir::Time | QDir::Reversed);
const auto excessFileCount = files.size() - maxFileCount;
for(auto i = 0; i < excessFileCount; ++i) {
const auto &fileInfo = files.at(i);
if(!m_logDir.remove(fileInfo.fileName())) {
fallbackMessageOutput(QStringLiteral("Failed to remove file: %1").arg(fileInfo.fileName()));
return false;
}
}
return true;
}
|