dist_sink.h 2.4 KB

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