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
19namespace spdlog {
20
21// Async overflow policy - block by default.
22enum class async_overflow_policy
23{
24 block, // Block until message can be enqueued
25 overrun_oldest // Discard oldest message in the queue if full when trying to
26 // add new item.
27};
28
29namespace details {
30class thread_pool;
31}
32
33class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>, public logger
34{
35 friend class details::thread_pool;
36
37public:
38 template<typename It>
39 async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp,
40 async_overflow_policy overflow_policy = async_overflow_policy::block)
41 : logger(std::move(logger_name), begin, end)
42 , thread_pool_(std::move(tp))
43 , overflow_policy_(overflow_policy)
44 {}
45
46 async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp,
47 async_overflow_policy overflow_policy = async_overflow_policy::block);
48
49 async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,
50 async_overflow_policy overflow_policy = async_overflow_policy::block);
51
52 std::shared_ptr<logger> clone(std::string new_name) override;
53
54protected:
55 void sink_it_(const details::log_msg &msg) override;
56 void flush_() override;
57 void backend_sink_it_(const details::log_msg &incoming_log_msg);
58 void backend_flush_();
59
60private:
61 std::weak_ptr<details::thread_pool> thread_pool_;
62 async_overflow_policy overflow_policy_;
63};
64} // namespace spdlog
65
66#ifdef SPDLOG_HEADER_ONLY
67# include "async_logger-inl.h"
68#endif
69