spdlog/tests/test_sink.h

71 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
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
2023-09-29 05:20:26 +08:00
#include "spdlog/details/null_mutex.h"
#include "spdlog/fmt/fmt.h"
#include "spdlog/sinks/base_sink.h"
2018-05-23 02:59:27 +08:00
namespace spdlog {
namespace sinks {
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:
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_;
}
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_;
}
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
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:
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);
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
}
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>;
2023-09-25 21:40:05 +08:00
} // namespace sinks
} // namespace spdlog