1 | // |
2 | // Copyright(c) 2018 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 | #include "spdlog/fmt/fmt.h" |
11 | #include <chrono> |
12 | #include <mutex> |
13 | #include <thread> |
14 | |
15 | namespace spdlog { |
16 | namespace sinks { |
17 | |
18 | template<class Mutex> |
19 | class test_sink : public base_sink<Mutex> |
20 | { |
21 | const size_t lines_to_save = 100; |
22 | |
23 | public: |
24 | size_t msg_counter() |
25 | { |
26 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
27 | return msg_counter_; |
28 | } |
29 | |
30 | size_t flush_counter() |
31 | { |
32 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
33 | return flush_counter_; |
34 | } |
35 | |
36 | void set_delay(std::chrono::milliseconds delay) |
37 | { |
38 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
39 | delay_ = delay; |
40 | } |
41 | |
42 | // return last output without the eol |
43 | std::vector<std::string> lines() |
44 | { |
45 | std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_); |
46 | return lines_; |
47 | } |
48 | |
49 | protected: |
50 | void sink_it_(const details::log_msg &msg) override |
51 | { |
52 | memory_buf_t formatted; |
53 | base_sink<Mutex>::formatter_->format(msg, formatted); |
54 | // save the line without the eol |
55 | auto eol_len = strlen(details::os::default_eol); |
56 | if (lines_.size() < lines_to_save) |
57 | { |
58 | lines_.emplace_back(formatted.begin(), formatted.end() - eol_len); |
59 | } |
60 | msg_counter_++; |
61 | std::this_thread::sleep_for(delay_); |
62 | } |
63 | |
64 | void flush_() override |
65 | { |
66 | flush_counter_++; |
67 | } |
68 | |
69 | size_t msg_counter_{0}; |
70 | size_t flush_counter_{0}; |
71 | std::chrono::milliseconds delay_{std::chrono::milliseconds::zero()}; |
72 | std::vector<std::string> lines_; |
73 | }; |
74 | |
75 | using test_sink_mt = test_sink<std::mutex>; |
76 | using test_sink_st = test_sink<details::null_mutex>; |
77 | |
78 | } // namespace sinks |
79 | } // namespace spdlog |
80 | |