-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.cpp
More file actions
92 lines (73 loc) · 1.67 KB
/
logger.cpp
File metadata and controls
92 lines (73 loc) · 1.67 KB
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
#include "pch.h"
#include "logger.h"
#include <iostream>
// initialization of static members
std::queue<std::string> eddft3::Logger::queue;
std::mutex eddft3::Logger::mutex;
std::condition_variable eddft3::Logger::cv;
std::thread eddft3::Logger::worker;
std::atomic<bool> eddft3::Logger::running{ false };
FILE* eddft3::Logger::consoleOut = nullptr;
void eddft3::Logger::initialize()
{
if (running) return;
AllocConsole();
// disable close button to prevent ES closing
HWND hwnd = GetConsoleWindow();
if (hwnd != NULL)
{
HMENU hMenu = GetSystemMenu(hwnd, FALSE);
if (hMenu != NULL)
{
DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
}
SetWindowTextA(hwnd, "eddft3 Logger");
}
freopen_s(&consoleOut, "CONOUT$", "w", stdout);
// create thread
running = true;
worker = std::thread(workerThread);
log("Logger initialized successfully.");
}
void eddft3::Logger::shutdown()
{
if (!running) return;
// signal thread stopping
running = false;
cv.notify_all();
// wait on closing thread
if (worker.joinable()) worker.join();
if (consoleOut)
{
fclose(consoleOut);
consoleOut = nullptr;
}
FreeConsole();
}
void eddft3::Logger::log(const std::string& message)
{
if (!running) return;
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(message);
}
cv.notify_one();
}
void eddft3::Logger::workerThread()
{
while (running)
{
std::string msg;
// wait if queue is not empty or if worker is not running
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [] { return !queue.empty() || !running; });
if (!running && queue.empty())
break;
msg = queue.front();
queue.pop();
}
// send the msg
std::cout << msg << std::endl;
}
}