forked from 2600hz/kazoo-popup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.cpp
111 lines (89 loc) · 2.32 KB
/
logger.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "logger.h"
#include "defaults.h"
#include <QMutexLocker>
#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <QDate>
#include <iostream>
static const char * const kLogFileNameTemplate = "'%1_'yyMMdd'.log'";
Logger *Logger::m_instance = nullptr;
void msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg)
{
Q_UNUSED(ctx);
Logger::instance()->handleMessage(type, msg);
}
Logger::Logger(QObject *parent) :
QObject(parent)
{
}
Logger::~Logger()
{
}
Logger *Logger::instance()
{
if (m_instance == nullptr)
{
static QMutex mutex;
mutex.lock();
if (m_instance == nullptr)
m_instance = new Logger;
mutex.unlock();
}
return m_instance;
}
void Logger::start()
{
qInstallMessageHandler(msgHandler);
}
void Logger::stop()
{
qInstallMessageHandler(0);
}
void Logger::handleMessage(QtMsgType type, const QString &msg)
{
QMutexLocker locker(&m_mutex);
//Create file with date addition
QString fileName = logsDirPath() + QDate::currentDate().toString(logFileNameTemplate());
QFile file(fileName);
if (!file.open(QIODevice::Append | QIODevice::Text))
return;
QTextStream stream(&file);
QString datetime = QDateTime::currentDateTime().toString(Qt::ISODate);
QString log;
switch (type)
{
case QtDebugMsg:
log = QString("[DEBUG] %1: %2\n").arg(datetime).arg(msg);
break;
case QtWarningMsg:
log = QString("[WARNING] %1: %2\n").arg(datetime).arg(msg);
break;
case QtCriticalMsg:
log = QString("[CRITICAL] %1: %2\n").arg(datetime).arg(msg);
break;
case QtFatalMsg:
log = QString("[FATAL] %1: %2\n").arg(datetime).arg(msg);
abort();
}
std::cout << msg.toLatin1().data() << std::endl;
stream << log;
emit newLog(log);
file.close();
}
QString Logger::logFileNameTemplate()
{
return QString(kLogFileNameTemplate).arg(qApp->applicationName());
}
QString Logger::logs() const
{
QString fileName = logsDirPath() + QDate::currentDate().toString(logFileNameTemplate());
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return QString();
QTextStream stream(&file);
QString data = stream.readAll();
data = data.trimmed();
file.close();
return data;
}