test_sink.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Copyright(c) 2018 Gabi Melman.
  3. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  4. //
  5. #pragma once
  6. #include "spdlog/details/null_mutex.h"
  7. #include "spdlog/sinks/base_sink.h"
  8. #include "spdlog/fmt/fmt.h"
  9. #include <chrono>
  10. #include <mutex>
  11. #include <thread>
  12. namespace spdlog {
  13. namespace sinks {
  14. template <class Mutex>
  15. class test_sink : public base_sink<Mutex> {
  16. const size_t lines_to_save = 100;
  17. public:
  18. size_t msg_counter() {
  19. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  20. return msg_counter_;
  21. }
  22. size_t flush_counter() {
  23. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  24. return flush_counter_;
  25. }
  26. void set_delay(std::chrono::milliseconds delay) {
  27. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  28. delay_ = delay;
  29. }
  30. // return last output without the eol
  31. std::vector<std::string> lines() {
  32. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  33. return lines_;
  34. }
  35. protected:
  36. void sink_it_(const details::log_msg &msg) override {
  37. memory_buf_t formatted;
  38. base_sink<Mutex>::formatter_->format(msg, formatted);
  39. // save the line without the eol
  40. auto eol_len = strlen(details::os::default_eol);
  41. if (lines_.size() < lines_to_save) {
  42. lines_.emplace_back(formatted.begin(), formatted.end() - eol_len);
  43. }
  44. msg_counter_++;
  45. std::this_thread::sleep_for(delay_);
  46. }
  47. void flush_() override { flush_counter_++; }
  48. size_t msg_counter_{0};
  49. size_t flush_counter_{0};
  50. std::chrono::milliseconds delay_{std::chrono::milliseconds::zero()};
  51. std::vector<std::string> lines_;
  52. };
  53. using test_sink_mt = test_sink<std::mutex>;
  54. using test_sink_st = test_sink<details::null_mutex>;
  55. } // namespace sinks
  56. } // namespace spdlog