dist_sink.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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> sink)
  27. {
  28. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  29. sinks_.push_back(sink);
  30. }
  31. void remove_sink(std::shared_ptr<sink> sink)
  32. {
  33. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  34. sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), 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 &sink : sinks_)
  49. {
  50. if (sink->should_log(msg.level))
  51. {
  52. sink->log(msg);
  53. }
  54. }
  55. }
  56. void flush_() override
  57. {
  58. for (auto &sink : sinks_)
  59. {
  60. 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 &sink : sinks_)
  71. {
  72. 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