| 1 | // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. |
| 2 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | // Fast asynchronous logger. |
| 7 | // Uses pre allocated queue. |
| 8 | // Creates a single back thread to pop messages from the queue and log them. |
| 9 | // |
| 10 | // Upon each log write the logger: |
| 11 | // 1. Checks if its log level is enough to log the message |
| 12 | // 2. Push a new copy of the message to a queue (or block the caller until |
| 13 | // space is available in the queue) |
| 14 | // Upon destruction, logs all remaining messages in the queue before |
| 15 | // destructing.. |
| 16 | |
| 17 | #include <spdlog/logger.h> |
| 18 | |
| 19 | namespace spdlog { |
| 20 | |
| 21 | // Async overflow policy - block by default. |
| 22 | enum class async_overflow_policy { |
| 23 | block, // Block until message can be enqueued |
| 24 | overrun_oldest, // Discard oldest message in the queue if full when trying to |
| 25 | // add new item. |
| 26 | discard_new // Discard new message if the queue is full when trying to add new item. |
| 27 | }; |
| 28 | |
| 29 | namespace details { |
| 30 | class thread_pool; |
| 31 | } |
| 32 | |
| 33 | class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>, |
| 34 | public logger { |
| 35 | friend class details::thread_pool; |
| 36 | |
| 37 | public: |
| 38 | template <typename It> |
| 39 | async_logger(std::string logger_name, |
| 40 | It begin, |
| 41 | It end, |
| 42 | std::weak_ptr<details::thread_pool> tp, |
| 43 | async_overflow_policy overflow_policy = async_overflow_policy::block) |
| 44 | : logger(std::move(logger_name), begin, end), |
| 45 | thread_pool_(std::move(tp)), |
| 46 | overflow_policy_(overflow_policy) {} |
| 47 | |
| 48 | async_logger(std::string logger_name, |
| 49 | sinks_init_list sinks_list, |
| 50 | std::weak_ptr<details::thread_pool> tp, |
| 51 | async_overflow_policy overflow_policy = async_overflow_policy::block); |
| 52 | |
| 53 | async_logger(std::string logger_name, |
| 54 | sink_ptr single_sink, |
| 55 | std::weak_ptr<details::thread_pool> tp, |
| 56 | async_overflow_policy overflow_policy = async_overflow_policy::block); |
| 57 | |
| 58 | std::shared_ptr<logger> clone(std::string new_name) override; |
| 59 | |
| 60 | protected: |
| 61 | void sink_it_(const details::log_msg &msg) override; |
| 62 | void flush_() override; |
| 63 | void backend_sink_it_(const details::log_msg &incoming_log_msg); |
| 64 | void backend_flush_(); |
| 65 | |
| 66 | private: |
| 67 | std::weak_ptr<details::thread_pool> thread_pool_; |
| 68 | async_overflow_policy overflow_policy_; |
| 69 | }; |
| 70 | } // namespace spdlog |
| 71 | |
| 72 | #ifdef SPDLOG_HEADER_ONLY |
| 73 | #include "async_logger-inl.h" |
| 74 | #endif |
| 75 | |