diff --git a/include/log_queue.h b/include/log_queue.h index 1c8ba7a..3747559 100644 --- a/include/log_queue.h +++ b/include/log_queue.h @@ -5,6 +5,7 @@ #include #include #include +#include class log_queue { @@ -12,7 +13,7 @@ private: std::thread _worker; std::mutex _mutex; std::condition_variable _cond; - std::queue _queue; + std::queue> _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& logFunc); }; #endif /* LOG_QUEUE_H */ diff --git a/include/logger.h b/include/logger.h index ef6c106..c93c4af 100644 --- a/include/logger.h +++ b/include/logger.h @@ -7,20 +7,32 @@ #include #include #include +#include class logger { private: + std::atomic _enabled; std::stringstream _logLine; log_queue _queue; public: logger(); + + void set_enabled(bool enabled) + { + _enabled = enabled; + } template 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: diff --git a/src/log_queue.cpp b/src/log_queue.cpp index 9132850..2ab9734 100644 --- a/src/log_queue.cpp +++ b/src/log_queue.cpp @@ -16,18 +16,17 @@ void log_queue::worker_func() { std::unique_lock lock(_mutex); _cond.wait(lock, [this] { return !_queue.empty(); }); - std::string line = _queue.front(); + std::function 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& logFunc) { std::lock_guard lock(_mutex); - _queue.push(logLine); + _queue.push(logFunc); _cond.notify_one(); } \ No newline at end of file diff --git a/src/logger.cpp b/src/logger.cpp index 013f1f3..5e9adf2 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -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; }