72 lines
1.7 KiB
C++
72 lines
1.7 KiB
C++
#pragma once
|
|
#include <iostream>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <queue>
|
|
#include <atomic>
|
|
#include <sstream> // <--- TO JEST NIEZBĘDNE
|
|
|
|
class AsyncLogger {
|
|
public:
|
|
static AsyncLogger& getInstance() {
|
|
static AsyncLogger instance;
|
|
return instance;
|
|
}
|
|
|
|
void log(const std::string& message) {
|
|
std::lock_guard<std::mutex> lock(queueMutex);
|
|
logQueue.push(message);
|
|
cv.notify_one();
|
|
}
|
|
|
|
void start() {
|
|
if (running) return;
|
|
running = true;
|
|
loggingThread = std::thread(&AsyncLogger::processQueue, this);
|
|
}
|
|
|
|
void stop() {
|
|
running = false;
|
|
cv.notify_one();
|
|
if (loggingThread.joinable()) {
|
|
loggingThread.join();
|
|
}
|
|
}
|
|
|
|
private:
|
|
AsyncLogger() : running(false) {}
|
|
~AsyncLogger() { stop(); }
|
|
|
|
void processQueue() {
|
|
while (running || !logQueue.empty()) {
|
|
std::unique_lock<std::mutex> lock(queueMutex);
|
|
cv.wait(lock, [this] { return !logQueue.empty() || !running; });
|
|
|
|
while (!logQueue.empty()) {
|
|
std::string msg = logQueue.front();
|
|
logQueue.pop();
|
|
lock.unlock();
|
|
|
|
std::cout << msg << std::endl;
|
|
|
|
lock.lock();
|
|
}
|
|
}
|
|
}
|
|
|
|
std::thread loggingThread;
|
|
std::mutex queueMutex;
|
|
std::condition_variable cv;
|
|
std::queue<std::string> logQueue;
|
|
std::atomic<bool> running;
|
|
};
|
|
|
|
// --- POPRAWIONE MAKRO ---
|
|
// Tworzy tymczasowy strumień (ostringstream), który "rozumie" operator <<
|
|
#define LOG(stream_args) { \
|
|
std::ostringstream ss; \
|
|
ss << stream_args; \
|
|
AsyncLogger::getInstance().log(ss.str()); \
|
|
} |