spdlog/tests/test_sink.h

70 lines
1.8 KiB
C
Raw Normal View History

2018-05-23 02:59:27 +08:00
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
#include "spdlog/details/null_mutex.h"
#include "spdlog/sinks/base_sink.h"
2019-08-27 22:18:09 +08:00
#include "spdlog/fmt/fmt.h"
2018-05-27 07:53:16 +08:00
#include <chrono>
2018-05-23 02:59:27 +08:00
#include <mutex>
2018-05-27 07:53:16 +08:00
#include <thread>
2018-05-23 02:59:27 +08:00
namespace spdlog {
namespace sinks {
2023-09-25 21:08:29 +08:00
template <class Mutex>
class test_sink : public base_sink<Mutex> {
2019-08-28 01:22:07 +08:00
const size_t lines_to_save = 100;
2018-05-23 02:59:27 +08:00
public:
2023-09-25 21:08:29 +08:00
size_t msg_counter() {
2018-08-14 05:58:50 +08:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-23 02:59:27 +08:00
return msg_counter_;
}
2023-09-25 21:08:29 +08:00
size_t flush_counter() {
2018-08-14 05:58:50 +08:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-27 07:53:16 +08:00
return flush_counter_;
}
2023-09-25 21:08:29 +08:00
void set_delay(std::chrono::milliseconds delay) {
2019-08-28 01:22:07 +08:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-27 07:53:16 +08:00
delay_ = delay;
2018-05-23 02:59:27 +08:00
}
2019-08-28 01:22:07 +08:00
// return last output without the eol
2023-09-25 21:08:29 +08:00
std::vector<std::string> lines() {
2019-08-28 01:22:07 +08:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
return lines_;
}
2019-08-27 22:18:09 +08:00
2018-05-23 02:59:27 +08:00
protected:
2023-09-25 21:08:29 +08:00
void sink_it_(const details::log_msg &msg) override {
memory_buf_t formatted;
2019-08-28 01:22:07 +08:00
base_sink<Mutex>::formatter_->format(msg, formatted);
// save the line without the eol
auto eol_len = strlen(details::os::default_eol);
2023-09-25 21:08:29 +08:00
if (lines_.size() < lines_to_save) {
2019-08-28 01:22:07 +08:00
lines_.emplace_back(formatted.begin(), formatted.end() - eol_len);
}
msg_counter_++;
std::this_thread::sleep_for(delay_);
2018-05-23 02:59:27 +08:00
}
2023-09-25 21:08:29 +08:00
void flush_() override { flush_counter_++; }
2019-08-28 01:22:07 +08:00
2018-05-23 02:59:27 +08:00
size_t msg_counter_{0};
2018-05-27 07:53:16 +08:00
size_t flush_counter_{0};
2018-07-23 05:13:24 +08:00
std::chrono::milliseconds delay_{std::chrono::milliseconds::zero()};
2019-08-28 01:22:07 +08:00
std::vector<std::string> lines_;
2018-05-23 02:59:27 +08:00
};
using test_sink_mt = test_sink<std::mutex>;
using test_sink_st = test_sink<details::null_mutex>;
} // namespace sinks
} // namespace spdlog