2023-06-01 10:50:42 -04:00
|
|
|
#include "logger.h"
|
|
|
|
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <QDateTime>
|
2023-06-01 10:50:42 -04:00
|
|
|
#include <QDebug>
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <QGlobalStatic>
|
|
|
|
#include <QIODevice>
|
2023-06-01 10:50:42 -04:00
|
|
|
#include <QStandardPaths>
|
2024-06-04 14:47:11 -04:00
|
|
|
|
|
|
|
#include <cstdio>
|
2023-06-01 14:14:06 -04:00
|
|
|
#include <iostream>
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <string>
|
2023-06-01 10:50:42 -04:00
|
|
|
|
2024-06-24 18:49:23 -04:00
|
|
|
using namespace Qt::Literals::StringLiterals;
|
|
|
|
|
2023-06-01 10:50:42 -04:00
|
|
|
class MyLogger: public Logger { };
|
|
|
|
Q_GLOBAL_STATIC(MyLogger, loggerInstance)
|
|
|
|
Logger *Logger::globalInstance()
|
|
|
|
{
|
|
|
|
return loggerInstance();
|
|
|
|
}
|
|
|
|
|
|
|
|
Logger::Logger()
|
|
|
|
{
|
|
|
|
// Get log file dir
|
|
|
|
auto dir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
|
|
|
|
// Remove old log file
|
|
|
|
QFile::remove(dir+"/log-prev.txt");
|
|
|
|
QFile::rename(dir+"/log.txt", dir+"/log-prev.txt");
|
|
|
|
// Open new log file
|
|
|
|
m_file.setFileName(dir+"/log.txt");
|
|
|
|
if (!m_file.open(QIODevice::NewOnly | QIODevice::WriteOnly | QIODevice::Text)) {
|
|
|
|
qWarning() << "Failed to open log file, logging to stdout...";
|
|
|
|
m_file.open(stdout, QIODevice::WriteOnly | QIODevice::Text);
|
|
|
|
}
|
|
|
|
// On success, install message handler
|
|
|
|
qInstallMessageHandler(Logger::messageHandler);
|
|
|
|
}
|
|
|
|
|
|
|
|
void Logger::messageHandler(QtMsgType type, const QMessageLogContext &, const QString &msg)
|
|
|
|
{
|
|
|
|
auto logger = globalInstance();
|
|
|
|
// Get message type as string
|
|
|
|
QString typeString;
|
|
|
|
switch (type) {
|
|
|
|
case QtDebugMsg:
|
|
|
|
typeString = "Debug";
|
|
|
|
break;
|
|
|
|
case QtInfoMsg:
|
|
|
|
typeString = "Info";
|
|
|
|
break;
|
|
|
|
case QtWarningMsg:
|
|
|
|
typeString = "Warning";
|
|
|
|
break;
|
|
|
|
case QtCriticalMsg:
|
|
|
|
typeString = "Critical";
|
|
|
|
break;
|
|
|
|
case QtFatalMsg:
|
|
|
|
typeString = "Fatal";
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
typeString = "???";
|
|
|
|
}
|
|
|
|
// Get time and date
|
|
|
|
auto timestamp = QDateTime::currentDateTime().toString();
|
|
|
|
// Write message
|
2024-06-24 18:49:23 -04:00
|
|
|
const std::string out = u"[%1] (%2): %3\n"_s.arg(typeString, timestamp, msg).toStdString();
|
2023-06-01 14:14:06 -04:00
|
|
|
logger->m_file.write(out.c_str());
|
2023-06-01 10:50:42 -04:00
|
|
|
logger->m_file.flush();
|
2023-06-01 14:14:06 -04:00
|
|
|
std::cerr << out;
|
|
|
|
fflush(stderr);
|
2023-06-01 10:50:42 -04:00
|
|
|
}
|