From ba2f2cbc1c99e497c65e0b03f9c2e27211bff78b Mon Sep 17 00:00:00 2001 From: irene Date: Sat, 15 Jul 2023 12:24:09 +0800 Subject: [PATCH] implemented async_logger::sync() --- include/spdlog/async_logger-inl.h | 34 +++++++++++++++++++++++++++++++ include/spdlog/async_logger.h | 8 ++++++++ 2 files changed, 42 insertions(+) diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index 4de8382a..36dec2ad 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -13,6 +13,8 @@ #include #include +#include + SPDLOG_INLINE spdlog::async_logger::async_logger( std::string logger_name, sinks_init_list sinks_list, std::weak_ptr tp, async_overflow_policy overflow_policy) : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) @@ -88,3 +90,35 @@ SPDLOG_INLINE std::shared_ptr spdlog::async_logger::clone(std::s cloned->name_ = std::move(new_name); return cloned; } + +SPDLOG_INLINE bool spdlog::async_logger::sync(int intervalMs, int timeoutMs) +{ + using namespace std::chrono; + + auto tp=thread_pool_.lock(); + assert(tp); + + if (tp->queue_size()==0) + return true; + + auto start=steady_clock::now(); + bool synced=false; + bool indef=(timeoutMs<=0); + do + { + if (!indef && intervalMs>timeoutMs) + intervalMs=timeoutMs; + + std::this_thread::sleep_for(milliseconds(intervalMs)); + synced=(tp->queue_size()==0); + + if (!indef) + { + auto now=steady_clock::now(); + auto passedMs=duration_cast(now-start); + start=now; + timeoutMs-=passedMs.count(); + } + } while ((!indef && timeoutMs>0 || indef) && !synced); + return synced; +} diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h index 91a93fcb..c83b9db0 100644 --- a/include/spdlog/async_logger.h +++ b/include/spdlog/async_logger.h @@ -51,6 +51,14 @@ public: std::shared_ptr clone(std::string new_name) override; + /** + * @brief block until all messages in thread_pool_ are processed + * @param intervalMs check whether should return or not on every 'intervalMs' milliseconds + * @param timeoutMs timeout in milliseconds. -1 means to wait indefinitely + * @return true: all messages in thread_pool_ are processed, false: otherwise + */ + bool sync(int intervalMs=100, int timeoutMs=-1); + protected: void sink_it_(const details::log_msg &msg) override; void flush_() override;