1 //
2 // Copyright(c) 2015 Gabi Melman.
3 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
4 //
5 
6 #pragma once
7 
8 #include "spdlog/details/null_mutex.h"
9 #include "spdlog/sinks/base_sink.h"
10 
11 #include <mutex>
12 #include <ostream>
13 
14 namespace spdlog {
15 namespace sinks {
16 template<typename Mutex>
17 class ostream_sink SPDLOG_FINAL : public base_sink<Mutex>
18 {
19 public:
ostream_sink(std::ostream &os, bool force_flush = false)20     explicit ostream_sink(std::ostream &os, bool force_flush = false)
21         : ostream_(os)
22         , force_flush_(force_flush)
23     {
24     }
25     ostream_sink(const ostream_sink &) = delete;
26     ostream_sink &operator=(const ostream_sink &) = delete;
27 
28 protected:
29     void sink_it_(const details::log_msg &msg) override
30     {
31         fmt::memory_buffer formatted;
32         sink::formatter_->format(msg, formatted);
33         ostream_.write(formatted.data(), formatted.size());
34         if (force_flush_)
35             ostream_.flush();
36     }
37 
38     void flush_() override
39     {
40         ostream_.flush();
41     }
42 
43     std::ostream &ostream_;
44     bool force_flush_;
45 };
46 
47 using ostream_sink_mt = ostream_sink<std::mutex>;
48 using ostream_sink_st = ostream_sink<details::null_mutex>;
49 
50 } // namespace sinks
51 } // namespace spdlog
52