Added Logger class acting as threadsafe wrapper for QDebug

This commit is contained in:
Albert S. 2019-04-16 08:46:39 +02:00
parent 02ce27fc9f
commit dce13706e1
2 changed files with 84 additions and 0 deletions

38
cli/logger.cpp Normal file
View File

@ -0,0 +1,38 @@
#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;
}

46
cli/logger.h Normal file
View File

@ -0,0 +1,46 @@
#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