add logger

This commit is contained in:
Jan Grewe 2023-11-10 11:04:42 +01:00
parent 5e958e710f
commit 4ae2945002
2 changed files with 96 additions and 0 deletions

63
mylogger.cpp Normal file
View File

@ -0,0 +1,63 @@
//This file is modified from "https://github.com/VelazcoJD/QtLogging"
#include "mylogger.h"
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QHash>
#include <QObject>
QFile* Logger::logFile = Q_NULLPTR;
bool Logger::isInit = false;
QHash<QtMsgType, QString> Logger::contextNames = {
{QtMsgType::QtDebugMsg, " Debug "},
{QtMsgType::QtInfoMsg, " Info "},
{QtMsgType::QtWarningMsg, "Warning "},
{QtMsgType::QtCriticalMsg, "Critical"},
{QtMsgType::QtFatalMsg, " Fatal "}
};
void Logger::init() {
if (isInit) {
return;
}
// Create log file
logFile = new QFile;
logFile->setFileName("./PylonRecorder.log");
logFile->open(QIODevice::Append | QIODevice::Text);
// Redirect logs to messageOutput
qInstallMessageHandler(Logger::messageOutput);
// Clear file contents
logFile->resize(0);
Logger::isInit = true;
}
void Logger::clean() {
if (logFile != Q_NULLPTR) {
logFile->close();
delete logFile;
}
}
void Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QString log = QObject::tr("%1 | %2 | %3 | %4 | %5 | %6\n").
arg(QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss")).
arg(Logger::contextNames.value(type)).
arg(context.line).
arg(QString(context.file).
section('/', -1)). // File name without file path
arg(QString(context.function).
section('(', -2, -2). // Function name only
section(' ', -1).
section(':', -1)).
arg(msg);
logFile->write(log.toLocal8Bit());
logFile->flush();
}

33
mylogger.h Normal file
View File

@ -0,0 +1,33 @@
//This file is modified from "https://github.com/VelazcoJD/QtLogging"
#ifndef MYLOGGER_H
#define MYLOGGER_H
#include <QDebug>
#include <QFile>
#include <QHash>
class Logger {
private:
/// @brief The file object where logs are written to.
static QFile* logFile;
/// @brief Whether the logger has being initialized.
static bool isInit;
/// @brief The different type of contexts.
static QHash<QtMsgType, QString> contextNames;
public:
/// @brief Initializes the logger.
static void init();
/// @brief Cleans up the logger.
static void clean();
/// @brief The function which handles the logging of text.
static void messageOutput(QtMsgType type, const QMessageLogContext& context,
const QString& msg);
};
#endif /* !MYLOGGER_H */