Added Logger class acting as threadsafe wrapper for QDebug

This commit is contained in:
Albert S. 2019-04-16 08:46:39 +02:00
orang tua 1b6f000188
melakukan 60cc13c4b0
2 mengubah file dengan 79 tambahan dan 0 penghapusan

36
cli/logger.cpp Normal file
Melihat File

@ -0,0 +1,36 @@
#include <QMutexLocker>
#include "logger.h"
Logger::Logger(QFile *file)
{
out = new QDebug(file);
this->file = file;
}
Logger::Logger(Logger &&o)
{
this->out = o.out;
o.out = nullptr;
}
Logger &Logger::error()
{
static Logger result = []
{
QFile *file = new QFile();
file->open(stderr, QIODevice::WriteOnly);
return Logger(file);
}();
return result;
}
Logger &Logger::info()
{
static Logger result = []
{
QFile *file = new QFile();
file->open(stdout, QIODevice::WriteOnly);
return Logger(file);
}();
return result;
}

43
cli/logger.h Normal file
Melihat File

@ -0,0 +1,43 @@
#ifndef LOGGER_H
#define LOGGER_H
#include <QFile>
#include <QDebug>
#include <QMutex>
class Logger
{
private:
QDebug *out;
QMutex mutex;
QFile *file;
public:
Logger(QFile *file);
Logger(Logger &&o);
template <class T> Logger &operator<<(const T &val)
{
QMutexLocker locker(&this->mutex);
*out << val;
file->flush();
return *this;
}
template <class T> Logger &operator<<(const T *val)
{
QMutexLocker locker(&this->mutex);
*out << val;
file->flush();
return *this;
}
~Logger()
{
delete out;
}
static Logger &error();
static Logger &info();
};
#endif // LOGGER_H