-
Notifications
You must be signed in to change notification settings - Fork 12
/
Logger.cpp
83 lines (67 loc) · 1.4 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
#include <QThread>
#include <QMutexLocker>
#include "Logger.h"
Logger::Logger(LoggerSink* sink /*= nullptr*/)
{
m_level = LOG_FATAL;
m_sink = sink;
m_threadState = STATE_RUNNING;
start();
}
Logger::~Logger()
{
// Set the logger thread as terminated
m_threadState = STATE_TERMINATED;
// Notify the thread
m_condition.wakeOne();
// Wait for termination
wait();
}
void Logger::setLevel(LoggerLevel level)
{
m_level = level;
}
LoggerLevel Logger::getLevel() const
{
return m_level;
}
void Logger::setSink(LoggerSink& sink)
{
m_sink = &sink;
}
LoggerSink& Logger::getSink()
{
return *m_sink;
}
void Logger::log(LoggerLevel level, const QString& message)
{
QMutexLocker locker(&m_mutex);
bool notify = m_queue.empty();
if(level <= m_level)
{
LogEntry entry =
{
level,
message
};
m_queue.push_back(entry);
if(notify)
m_condition.wakeOne();
}
}
void Logger::run()
{
while(m_threadState != STATE_TERMINATED)
{
QMutexLocker locker(&m_mutex);
if(m_queue.empty())
{
m_condition.wait(&m_mutex);
}
if(m_threadState == STATE_TERMINATED || m_queue.empty())
continue;
Logger::LogEntry entry = m_queue.front();
m_queue.pop_front();
m_sink->write(entry.logLevel, entry.logMessage);
}
}