summaryrefslogtreecommitdiff
path: root/lib/spdlog/sinks/dist_sink.h
blob: b4a7b6a1f4133ba351abf64ca1a6d77367febf9a (plain)
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
71
72
73
74
75
76
77
//
// Copyright (c) 2015 David Schury, Gabi Melman
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#pragma once

#include "../details/log_msg.h"
#include "../details/null_mutex.h"
#include "base_sink.h"
#include "sink.h"

#include <algorithm>
#include <memory>
#include <mutex>
#include <vector>

// Distribution sink (mux). Stores a vector of sinks which get called when log is called

namespace spdlog {
namespace sinks {
template<class Mutex>
class dist_sink : public base_sink<Mutex>
{
public:
    explicit dist_sink()
        : _sinks()
    {
    }
    dist_sink(const dist_sink &) = delete;
    dist_sink &operator=(const dist_sink &) = delete;

protected:
    std::vector<std::shared_ptr<sink>> _sinks;

    void _sink_it(const details::log_msg &msg) override
    {
        for (auto &sink : _sinks)
        {
            if (sink->should_log(msg.level))
            {
                sink->log(msg);
            }
        }
    }

    void _flush() override
    {
        for (auto &sink : _sinks)
            sink->flush();
    }

public:
    void add_sink(std::shared_ptr<sink> sink)
    {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex);
        _sinks.push_back(sink);
    }

    void remove_sink(std::shared_ptr<sink> sink)
    {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex);
        _sinks.erase(std::remove(_sinks.begin(), _sinks.end(), sink), _sinks.end());
    }

    void remove_all_sinks()
    {
        std::lock_guard<Mutex> lock(base_sink<Mutex>::_mutex);
        _sinks.clear();
    }
};

using dist_sink_mt = dist_sink<std::mutex>;
using dist_sink_st = dist_sink<details::null_mutex>;

} // namespace sinks
} // namespace spdlog