diff --git a/include/log_queue.h b/include/log_queue.h new file mode 100644 index 0000000..1c8ba7a --- /dev/null +++ b/include/log_queue.h @@ -0,0 +1,27 @@ +#ifndef LOG_QUEUE_H +#define LOG_QUEUE_H + +#include +#include +#include +#include + +class log_queue +{ +private: + std::thread _worker; + std::mutex _mutex; + std::condition_variable _cond; + std::queue _queue; + +private: + void worker_func(); + +public: + log_queue(); + ~log_queue(); + void add_log(const std::string& logLine); +}; + +#endif /* LOG_QUEUE_H */ + diff --git a/include/logger.h b/include/logger.h index 9ffc694..ef6c106 100644 --- a/include/logger.h +++ b/include/logger.h @@ -1,6 +1,8 @@ #ifndef _LOGGER_H_ #define _LOGGER_H_ +#include "log_queue.h" + #include #include #include @@ -10,6 +12,7 @@ class logger { private: std::stringstream _logLine; + log_queue _queue; public: logger(); diff --git a/src/log_queue.cpp b/src/log_queue.cpp new file mode 100644 index 0000000..9132850 --- /dev/null +++ b/src/log_queue.cpp @@ -0,0 +1,33 @@ +#include "log_queue.h" +#include + +log_queue::log_queue(): _worker(&log_queue::worker_func, this) +{ +} + +log_queue::~log_queue() +{ + _worker.join(); +} + +void log_queue::worker_func() +{ + while(true) + { + std::unique_lock lock(_mutex); + _cond.wait(lock, [this] { return !_queue.empty(); }); + std::string line = _queue.front(); + _queue.pop(); + lock.unlock(); + + // actually logging + std::cout << line << std::endl; + } +} + +void log_queue::add_log(const std::string& logLine) +{ + std::lock_guard lock(_mutex); + _queue.push(logLine); + _cond.notify_one(); +} \ No newline at end of file diff --git a/src/logger.cpp b/src/logger.cpp index 5a85b7f..013f1f3 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -17,6 +17,6 @@ void logger::log_internal(const char *s) _logLine << *s++; } - std::cout << _logLine.str() << std::endl; + _queue.add_log(_logLine.str()); } diff --git a/test/main.cpp b/test/main.cpp index 3f9d962..892e3a8 100755 --- a/test/main.cpp +++ b/test/main.cpp @@ -571,5 +571,8 @@ int main(int argc, char **argv) ulog.log("one: %, two: %", one, two); ulog.log("Hello world!"); + int i = 0; + std::cin >> i; + return 0; }