1 //
2 // Copyright (c) 2015 David Schury, Gabi Melman
3 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
4 //
5 
6 #pragma once
7 
8 #include "base_sink.h"
9 #include "spdlog/details/log_msg.h"
10 #include "spdlog/details/null_mutex.h"
11 
12 #include <algorithm>
13 #include <memory>
14 #include <mutex>
15 #include <vector>
16 
17 // Distribution sink (mux). Stores a vector of sinks which get called when log
18 // is called
19 
20 namespace spdlog {
21 namespace sinks {
22 
23 template<typename Mutex>
24 class dist_sink : public base_sink<Mutex>
25 {
26 public:
27     dist_sink() = default;
28     dist_sink(const dist_sink &) = delete;
29     dist_sink &operator=(const dist_sink &) = delete;
30 
add_sink(std::shared_ptr<sink> sink)31     void add_sink(std::shared_ptr<sink> sink)
32     {
33         std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
34         sinks_.push_back(sink);
35     }
36 
remove_sink(std::shared_ptr<sink> sink)37     void remove_sink(std::shared_ptr<sink> sink)
38     {
39         std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
40         sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end());
41     }
42 
43 protected:
44     void sink_it_(const details::log_msg &msg) override
45     {
46 
47         for (auto &sink : sinks_)
48         {
49             if (sink->should_log(msg.level))
50             {
51                 sink->log(msg);
52             }
53         }
54     }
55 
56     void flush_() override
57     {
58         for (auto &sink : sinks_)
59             sink->flush();
60     }
61     std::vector<std::shared_ptr<sink>> sinks_;
62 };
63 
64 using dist_sink_mt = dist_sink<std::mutex>;
65 using dist_sink_st = dist_sink<details::null_mutex>;
66 
67 } // namespace sinks
68 } // namespace spdlog
69