-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncLogger.h
More file actions
83 lines (73 loc) · 2.15 KB
/
AsyncLogger.h
File metadata and controls
83 lines (73 loc) · 2.15 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
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <sstream>
class AsyncLogger {
public:
AsyncLogger() : exitFlag(false), queueFullWarningShown(false) {
worker = std::thread([this] {
processQueue();
});
}
~AsyncLogger() {
{
std::lock_guard<std::mutex> lock(queueMutex);
exitFlag = true;
}
cv.notify_one();
if (worker.joinable()) {
worker.join();
}
}
void log(const std::string& message) {
{
std::lock_guard<std::mutex> lock(queueMutex);
if (msgQueue.size() >= MAX_QUEUE_SIZE) {
if (!queueFullWarningShown) {
std::cerr << "[Security] AsyncLogger queue full (" << MAX_QUEUE_SIZE
<< " messages). Dropping logs to prevent DoS.\n";
queueFullWarningShown = true;
}
return;
}
msgQueue.push(message);
}
cv.notify_one();
}
private:
const size_t MAX_QUEUE_SIZE = 10000;
std::thread worker;
std::queue<std::string> msgQueue;
std::mutex queueMutex;
std::condition_variable cv;
bool exitFlag;
bool queueFullWarningShown;
void processQueue() {
while (true) {
std::unique_lock<std::mutex> lock(queueMutex);
cv.wait(lock, [this] { return !msgQueue.empty() || exitFlag; });
if (exitFlag && msgQueue.empty()) {
break;
}
// Process all messages in the queue to minimize locking
while (!msgQueue.empty()) {
std::string msg = std::move(msgQueue.front());
msgQueue.pop();
// Unlock while doing I/O
lock.unlock();
std::cout << msg << std::flush;
lock.lock();
}
// Reset warning flag when queue is empty
if (msgQueue.empty()) {
queueFullWarningShown = false;
}
}
}
};