Функция log теперь не формирует строку, а упаковывает параметры и код логирования в функтор и добавляет его в очередь, обрабатываемую отдельным потоком.
This commit is contained in:
parent
336e342c14
commit
966e729bf8
@ -5,6 +5,7 @@
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
|
||||
class log_queue
|
||||
{
|
||||
@ -12,7 +13,7 @@ private:
|
||||
std::thread _worker;
|
||||
std::mutex _mutex;
|
||||
std::condition_variable _cond;
|
||||
std::queue<std::string> _queue;
|
||||
std::queue<std::function<void()>> _queue;
|
||||
|
||||
private:
|
||||
void worker_func();
|
||||
@ -20,7 +21,7 @@ private:
|
||||
public:
|
||||
log_queue();
|
||||
~log_queue();
|
||||
void add_log(const std::string& logLine);
|
||||
void add_log(const std::function<void()>& logFunc);
|
||||
};
|
||||
|
||||
#endif /* LOG_QUEUE_H */
|
||||
|
||||
@ -7,20 +7,32 @@
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
|
||||
class logger
|
||||
{
|
||||
private:
|
||||
std::atomic<bool> _enabled;
|
||||
std::stringstream _logLine;
|
||||
log_queue _queue;
|
||||
|
||||
public:
|
||||
logger();
|
||||
|
||||
void set_enabled(bool enabled)
|
||||
{
|
||||
_enabled = enabled;
|
||||
}
|
||||
|
||||
template<typename... Args> void log(const char* s, const Args&... args)
|
||||
{
|
||||
_logLine.str("");
|
||||
log_internal(s, args...);
|
||||
if(_enabled)
|
||||
{
|
||||
_queue.add_log([this, s, &args...] {
|
||||
_logLine.str("");
|
||||
log_internal(s, args...);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@ -16,18 +16,17 @@ void log_queue::worker_func()
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_cond.wait(lock, [this] { return !_queue.empty(); });
|
||||
std::string line = _queue.front();
|
||||
std::function<void()> func = _queue.front();
|
||||
_queue.pop();
|
||||
lock.unlock();
|
||||
|
||||
// actually logging
|
||||
std::cout << line << std::endl;
|
||||
func();
|
||||
}
|
||||
}
|
||||
|
||||
void log_queue::add_log(const std::string& logLine)
|
||||
void log_queue::add_log(const std::function<void()>& logFunc)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
_queue.push(logLine);
|
||||
_queue.push(logFunc);
|
||||
_cond.notify_one();
|
||||
}
|
||||
@ -4,7 +4,7 @@
|
||||
|
||||
logger ulog;
|
||||
|
||||
logger::logger()
|
||||
logger::logger(): _enabled(true)
|
||||
{
|
||||
}
|
||||
|
||||
@ -17,6 +17,7 @@ void logger::log_internal(const char *s)
|
||||
_logLine << *s++;
|
||||
}
|
||||
|
||||
_queue.add_log(_logLine.str());
|
||||
// actually logging
|
||||
std::cout << _logLine.str() << std::endl;
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user