ostream_sink.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 <spdlog/details/null_mutex.h>
  5. #include <spdlog/sinks/base_sink.h>
  6. #include <mutex>
  7. #include <ostream>
  8. namespace spdlog {
  9. namespace sinks {
  10. template <typename Mutex>
  11. class ostream_sink final : public base_sink<Mutex> {
  12. public:
  13. explicit ostream_sink(std::ostream &os, bool force_flush = false)
  14. : ostream_(os),
  15. force_flush_(force_flush) {}
  16. ostream_sink(const ostream_sink &) = delete;
  17. ostream_sink &operator=(const ostream_sink &) = delete;
  18. protected:
  19. void sink_it_(const details::log_msg &msg) override {
  20. memory_buf_t formatted;
  21. base_sink<Mutex>::formatter_->format(msg, formatted);
  22. ostream_.write(formatted.data(), static_cast<std::streamsize>(formatted.size()));
  23. if (force_flush_) {
  24. ostream_.flush();
  25. }
  26. }
  27. void flush_() override { ostream_.flush(); }
  28. std::ostream &ostream_;
  29. bool force_flush_;
  30. };
  31. using ostream_sink_mt = ostream_sink<std::mutex>;
  32. using ostream_sink_st = ostream_sink<details::null_mutex>;
  33. } // namespace sinks
  34. } // namespace spdlog