Функция log теперь не формирует строку, а упаковывает параметры и код логирования в функтор и добавляет его в очередь, обрабатываемую отдельным потоком.

This commit is contained in:
selim 2014-08-24 23:59:41 +04:00
parent 336e342c14
commit 966e729bf8
4 changed files with 24 additions and 11 deletions

View File

@ -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 */

View File

@ -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)
{
if(_enabled)
{
_queue.add_log([this, s, &args...] {
_logLine.str("");
log_internal(s, args...);
});
}
}
private:

View File

@ -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();
}

View File

@ -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;
}