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 | #ifndef SPDLOG_HEADER_ONLY |
7 | # include <spdlog/async_logger.h> |
8 | #endif |
9 | |
10 | #include <spdlog/sinks/sink.h> |
11 | #include <spdlog/details/thread_pool.h> |
12 | |
13 | #include <memory> |
14 | #include <string> |
15 | |
16 | SPDLOG_INLINE spdlog::async_logger::async_logger( |
17 | std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) |
18 | : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy) |
19 | {} |
20 | |
21 | SPDLOG_INLINE spdlog::async_logger::async_logger( |
22 | std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) |
23 | : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) |
24 | {} |
25 | |
26 | // send the log message to the thread pool |
27 | SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg) |
28 | { |
29 | if (auto pool_ptr = thread_pool_.lock()) |
30 | { |
31 | pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); |
32 | } |
33 | else |
34 | { |
35 | throw_spdlog_ex("async log: thread pool doesn't exist anymore" ); |
36 | } |
37 | } |
38 | |
39 | // send flush request to the thread pool |
40 | SPDLOG_INLINE void spdlog::async_logger::flush_() |
41 | { |
42 | if (auto pool_ptr = thread_pool_.lock()) |
43 | { |
44 | pool_ptr->post_flush(shared_from_this(), overflow_policy_); |
45 | } |
46 | else |
47 | { |
48 | throw_spdlog_ex("async flush: thread pool doesn't exist anymore" ); |
49 | } |
50 | } |
51 | |
52 | // |
53 | // backend functions - called from the thread pool to do the actual job |
54 | // |
55 | SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg &msg) |
56 | { |
57 | for (auto &sink : sinks_) |
58 | { |
59 | if (sink->should_log(msg.level)) |
60 | { |
61 | SPDLOG_TRY |
62 | { |
63 | sink->log(msg); |
64 | } |
65 | SPDLOG_LOGGER_CATCH(msg.source) |
66 | } |
67 | } |
68 | |
69 | if (should_flush_(msg)) |
70 | { |
71 | backend_flush_(); |
72 | } |
73 | } |
74 | |
75 | SPDLOG_INLINE void spdlog::async_logger::backend_flush_() |
76 | { |
77 | for (auto &sink : sinks_) |
78 | { |
79 | SPDLOG_TRY |
80 | { |
81 | sink->flush(); |
82 | } |
83 | SPDLOG_LOGGER_CATCH(source_loc()) |
84 | } |
85 | } |
86 | |
87 | SPDLOG_INLINE std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name) |
88 | { |
89 | auto cloned = std::make_shared<spdlog::async_logger>(*this); |
90 | cloned->name_ = std::move(new_name); |
91 | return cloned; |
92 | } |
93 | |