aboutsummaryrefslogtreecommitdiff
path: root/thirdparty/spdlog/tests/test_sink.h
blob: 9c0945232a5adc99ed8d3019056fdef3b4c87b5e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// 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"
#include "spdlog/fmt/fmt.h"
#include <chrono>
#include <mutex>
#include <thread>

namespace spdlog {
namespace sinks {

template <class Mutex>
class test_sink : public base_sink<Mutex> {
    const size_t lines_to_save = 100;

public:
    size_t msg_counter() {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
        return msg_counter_;
    }

    size_t flush_counter() {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
        return flush_counter_;
    }

    void set_delay(std::chrono::milliseconds delay) {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
        delay_ = delay;
    }

    // return last output without the eol
    std::vector<std::string> lines() {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
        return lines_;
    }

protected:
    void sink_it_(const details::log_msg &msg) override {
        memory_buf_t formatted;
        base_sink<Mutex>::formatter_->format(msg, formatted);
        // save the line without the eol
        auto eol_len = strlen(details::os::default_eol);
        using diff_t = typename std::iterator_traits<decltype(formatted.end())>::difference_type;
        if (lines_.size() < lines_to_save) {
            lines_.emplace_back(formatted.begin(), formatted.end() - static_cast<diff_t>(eol_len));
        }
        msg_counter_++;
        std::this_thread::sleep_for(delay_);
    }

    void flush_() override { flush_counter_++; }

    size_t msg_counter_{0};
    size_t flush_counter_{0};
    std::chrono::milliseconds delay_{std::chrono::milliseconds::zero()};
    std::vector<std::string> lines_;
};

using test_sink_mt = test_sink<std::mutex>;
using test_sink_st = test_sink<details::null_mutex>;

}  // namespace sinks
}  // namespace spdlog