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 | #include "base_sink.h" |
7 | #include <spdlog/details/log_msg.h> |
8 | #include <spdlog/details/null_mutex.h> |
9 | #include <spdlog/pattern_formatter.h> |
10 | |
11 | #include <algorithm> |
12 | #include <memory> |
13 | #include <mutex> |
14 | #include <vector> |
15 | |
16 | // Distribution sink (mux). Stores a vector of sinks which get called when log |
17 | // is called |
18 | |
19 | namespace spdlog { |
20 | namespace sinks { |
21 | |
22 | template<typename Mutex> |
23 | class dist_sink : public base_sink<Mutex> |
24 | { |
25 | public: |
26 | dist_sink() = default; |
27 | explicit dist_sink(std::vector<std::shared_ptr<sink>> sinks) |
28 | : sinks_(sinks) |
29 | {} |
30 | |
31 | dist_sink(const dist_sink &) = delete; |
32 | dist_sink &operator=(const dist_sink &) = delete; |
33 | |
34 | void add_sink(std::shared_ptr<sink> sink) |
35 | { |
36 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
37 | sinks_.push_back(sink); |
38 | } |
39 | |
40 | void remove_sink(std::shared_ptr<sink> sink) |
41 | { |
42 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
43 | sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end()); |
44 | } |
45 | |
46 | void set_sinks(std::vector<std::shared_ptr<sink>> sinks) |
47 | { |
48 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
49 | sinks_ = std::move(sinks); |
50 | } |
51 | |
52 | std::vector<std::shared_ptr<sink>> &sinks() |
53 | { |
54 | return sinks_; |
55 | } |
56 | |
57 | protected: |
58 | void sink_it_(const details::log_msg &msg) override |
59 | { |
60 | for (auto &sub_sink : sinks_) |
61 | { |
62 | if (sub_sink->should_log(msg.level)) |
63 | { |
64 | sub_sink->log(msg); |
65 | } |
66 | } |
67 | } |
68 | |
69 | void flush_() override |
70 | { |
71 | for (auto &sub_sink : sinks_) |
72 | { |
73 | sub_sink->flush(); |
74 | } |
75 | } |
76 | |
77 | void set_pattern_(const std::string &pattern) override |
78 | { |
79 | set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern)); |
80 | } |
81 | |
82 | void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) override |
83 | { |
84 | base_sink<Mutex>::formatter_ = std::move(sink_formatter); |
85 | for (auto &sub_sink : sinks_) |
86 | { |
87 | sub_sink->set_formatter(base_sink<Mutex>::formatter_->clone()); |
88 | } |
89 | } |
90 | std::vector<std::shared_ptr<sink>> sinks_; |
91 | }; |
92 | |
93 | using dist_sink_mt = dist_sink<std::mutex>; |
94 | using dist_sink_st = dist_sink<details::null_mutex>; |
95 | |
96 | } // namespace sinks |
97 | } // namespace spdlog |
98 | |