59 lines
1.6 KiB
C++
59 lines
1.6 KiB
C++
#pragma once
|
|
|
|
#include <QDateTime>
|
|
#include <QFile>
|
|
#include <QMessageLogger>
|
|
#include <QString>
|
|
#include <QTextStream>
|
|
|
|
void logToFile(QtMsgType msgType, const QMessageLogContext& msgContext, const QString& msg)
|
|
{
|
|
constexpr auto LOG_FILE = "logfile.log";
|
|
|
|
const auto dateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
|
|
QString formattedMsg = QString("[%1] ").arg(dateTime);
|
|
|
|
switch(msgType) {
|
|
case QtDebugMsg:
|
|
formattedMsg += "[Debug] ";
|
|
break;
|
|
case QtWarningMsg:
|
|
formattedMsg += "[Warning] ";
|
|
break;
|
|
case QtCriticalMsg:
|
|
formattedMsg += "[Critical] ";
|
|
break;
|
|
case QtFatalMsg:
|
|
formattedMsg += "[Fatal] ";
|
|
break;
|
|
case QtInfoMsg:
|
|
formattedMsg += "[Info] ";
|
|
break;
|
|
}
|
|
|
|
const auto msgFromFile = QString(msgContext.file);
|
|
const auto msgFromLine = (msgContext.line == 0) ? QString("") : QString("%1").arg(msgContext.line);
|
|
const auto msgFromFunction = QString(msgContext.function);
|
|
|
|
if(!msgFromFile.isEmpty() && !msgFromLine.isEmpty()) {
|
|
formattedMsg += QString("[%1:%2] ").arg(msgContext.file).arg(msgContext.line);
|
|
}
|
|
if(!msgFromFunction.isEmpty()) {
|
|
formattedMsg += QString("[%1] ").arg(msgContext.function);
|
|
}
|
|
|
|
formattedMsg += QString("%1").arg(msg);
|
|
|
|
QFile logFile(LOG_FILE);
|
|
logFile.open(QIODevice::WriteOnly | QIODevice::Append);
|
|
|
|
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
|
|
constexpr auto qtEndl = Qt::endl;
|
|
#else
|
|
constexpr auto qtEndl = ::endl;
|
|
#endif
|
|
|
|
QTextStream textStream(&logFile);
|
|
textStream << formattedMsg << qtEndl;
|
|
}
|