Add logging to file
This commit is contained in:
parent
015ab15a02
commit
7310d212e6
58
AdaptiveBrightness/log_to_file.hpp
Normal file
58
AdaptiveBrightness/log_to_file.hpp
Normal file
@ -0,0 +1,58 @@
|
||||
#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;
|
||||
}
|
@ -1,9 +1,15 @@
|
||||
#include <QApplication>
|
||||
#include <QMessageLogger>
|
||||
#include <QtDebug>
|
||||
#include <QtGlobal>
|
||||
|
||||
#include "AdaptiveBrightness.hpp"
|
||||
#include "log_to_file.hpp"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
qInstallMessageHandler(logToFile);
|
||||
|
||||
QApplication application(argc, argv);
|
||||
AdaptiveBrightness mainWindow;
|
||||
mainWindow.show();
|
||||
|
Loading…
Reference in New Issue
Block a user