spdlog/tests/test_sink.h

80 lines
1.8 KiB
C
Raw Normal View History

2018-05-22 14:59:27 -04: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 10:18:09 -04:00
#include "spdlog/fmt/fmt.h"
2018-05-26 19:53:16 -04:00
#include <chrono>
2018-05-22 14:59:27 -04:00
#include <mutex>
2018-05-26 19:53:16 -04:00
#include <thread>
2018-05-22 14:59:27 -04:00
namespace spdlog {
namespace sinks {
template<class Mutex>
class test_sink : public base_sink<Mutex>
{
2019-08-27 13:22:07 -04:00
const size_t lines_to_save = 100;
2018-05-22 14:59:27 -04:00
public:
size_t msg_counter()
{
2018-08-13 17:58:50 -04:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-22 14:59:27 -04:00
return msg_counter_;
}
2018-05-26 19:53:16 -04:00
size_t flush_counter()
2018-05-22 14:59:27 -04:00
{
2018-08-13 17:58:50 -04:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-26 19:53:16 -04:00
return flush_counter_;
}
void set_delay(std::chrono::milliseconds delay)
{
2019-08-27 13:22:07 -04:00
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
2018-05-26 19:53:16 -04:00
delay_ = delay;
2018-05-22 14:59:27 -04:00
}
2019-08-27 13:22:07 -04:00
// return last output without the eol
std::vector<std::string> lines()
{
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
return lines_;
}
2019-08-27 10:18:09 -04:00
2018-05-22 14:59:27 -04:00
protected:
2019-08-27 10:18:09 -04:00
void sink_it_(const details::log_msg &msg) override
2019-08-27 13:22:07 -04:00
{
memory_buf_t formatted;
2019-08-27 13:22:07 -04: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)
{
lines_.emplace_back(formatted.begin(), formatted.end() - eol_len);
}
msg_counter_++;
std::this_thread::sleep_for(delay_);
2018-05-22 14:59:27 -04:00
}
void flush_() override
2018-05-22 14:59:27 -04:00
{
2018-05-26 19:53:16 -04:00
flush_counter_++;
2018-05-22 14:59:27 -04:00
}
2019-08-27 13:22:07 -04:00
2018-05-22 14:59:27 -04:00
size_t msg_counter_{0};
2018-05-26 19:53:16 -04:00
size_t flush_counter_{0};
2018-07-22 17:13:24 -04:00
std::chrono::milliseconds delay_{std::chrono::milliseconds::zero()};
2019-08-27 13:22:07 -04:00
std::vector<std::string> lines_;
2018-05-22 14:59:27 -04:00
};
using test_sink_mt = test_sink<std::mutex>;
using test_sink_st = test_sink<details::null_mutex>;
} // namespace sinks
} // namespace spdlog