From 4ae2945002c188da9127f4d4f82b43038a6b4a2d Mon Sep 17 00:00:00 2001 From: Jan Grewe Date: Fri, 10 Nov 2023 11:04:42 +0100 Subject: [PATCH] add logger --- mylogger.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ mylogger.h | 33 +++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 mylogger.cpp create mode 100644 mylogger.h diff --git a/mylogger.cpp b/mylogger.cpp new file mode 100644 index 0000000..11fb43b --- /dev/null +++ b/mylogger.cpp @@ -0,0 +1,63 @@ +//This file is modified from "https://github.com/VelazcoJD/QtLogging" + +#include "mylogger.h" + +#include +#include +#include +#include +#include + +QFile* Logger::logFile = Q_NULLPTR; +bool Logger::isInit = false; +QHash 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(); +} \ No newline at end of file diff --git a/mylogger.h b/mylogger.h new file mode 100644 index 0000000..65534f6 --- /dev/null +++ b/mylogger.h @@ -0,0 +1,33 @@ + +//This file is modified from "https://github.com/VelazcoJD/QtLogging" +#ifndef MYLOGGER_H +#define MYLOGGER_H + +#include +#include +#include + +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 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 */ \ No newline at end of file