forked from rigtorp/spartan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.hpp
247 lines (213 loc) · 6.83 KB
/
log.hpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/*
Copyright (c) 2015 Erik Rigtorp <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <atomic>
#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <mutex>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
class Formatter {
public:
static void format(std::ostream &o) { o << "\n"; }
template <typename T, typename... Args>
static void format(std::ostream &o, T &&t, Args &&... args) {
o << t << " ";
format(o, std::forward<Args>(args)...);
}
};
class Message {
public:
template <typename... Args> Message(Args &&... args) {
fp = pack(&data, std::forward<Args>(args)...);
}
~Message() {
// make sure destructors are called
fp(nullptr, &data);
}
void Format(std::ostream &o) { fp(&o, &data); }
private:
Message(Message &other) = delete;
Message &operator=(const Message &) = delete;
Message(Message &&other) = delete;
Message &operator=(Message &&) = delete;
template <typename Tup, std::size_t... index>
static void call_format_helper(std::ostream &o, Tup &&args,
std::index_sequence<index...>) {
Formatter::format(o, std::get<index>(std::forward<Tup>(args))...);
}
template <typename... Args>
static void call_format(std::ostream *o, void *p) {
typedef std::tuple<Args...> Tup;
Tup &args = *reinterpret_cast<Tup *>(p);
if (o) {
call_format_helper(*o, args, std::index_sequence_for<Args...>{});
} else {
// important to call destructor for complex types
args.~Tup();
}
}
template <typename T, typename... Args>
static decltype(auto) pack(T *p, Args &&... args) {
typedef std::tuple<typename std::decay<Args>::type...> Tup;
static_assert(alignof(Tup) <= alignof(T), "invalid alignment");
static_assert(sizeof(Tup) <= sizeof(T), "storage too small");
new (p) Tup(std::forward<Args>(args)...);
return &call_format<typename std::decay<Args>::type...>;
}
using FormatFun = void (*)(std::ostream *, void *);
using Storage = typename std::aligned_storage<56, 8>::type;
FormatFun fp;
Storage data;
};
static_assert(sizeof(Message) == 64, "message not a cache line in size");
template <typename T> class Queue {
// Ringbuffer, fixed size single producer single consumer lock-free queue
public:
Queue(const size_t size)
: size_(size), buffer_(static_cast<T *>(std::malloc(sizeof(T) * size))),
head_(0), tail_(0) {
if (!buffer_) {
throw std::bad_alloc();
}
}
~Queue() {
while (front()) {
pop();
}
std::free(buffer_);
}
template <typename... Args> void emplace(Args &&... args) {
auto const head = head_.load(std::memory_order_relaxed);
auto const next_head = (head + 1) % size_;
while (next_head == tail_.load(std::memory_order_acquire))
;
new (&buffer_[head]) T(std::forward<Args>(args)...);
head_.store(next_head, std::memory_order_release);
}
T *front() {
auto tail = tail_.load(std::memory_order_relaxed);
if (head_.load(std::memory_order_acquire) == tail) {
return nullptr;
}
return &buffer_[tail];
}
void pop() {
auto const tail = tail_.load(std::memory_order_relaxed);
if (head_.load(std::memory_order_acquire) == tail) {
return;
}
auto const next_tail = (tail + 1) % size_;
buffer_[tail].~T();
tail_.store(next_tail, std::memory_order_release);
}
private:
const size_t size_;
T *const buffer_;
std::atomic<size_t> head_, tail_;
};
class Logger {
public:
template <typename... Args>
static void Log(const char *fmt, Args &&... args) {
queue().emplace(fmt, std::forward<Args>(args)...);
}
static void SetQueueSize(const size_t size) { instance().queue_size_ = size; }
static void SetOutput(const std::string &fname) {
Logger &logger = instance();
std::lock_guard<std::mutex> lock(logger.mutex_);
if (fname == "") {
logger.ostream_.reset();
logger.cout_ = false;
} else if (fname == "-") {
logger.ostream_.reset();
logger.cout_ = true;
} else {
logger.ostream_ = std::make_unique<std::ofstream>(fname);
logger.cout_ = false;
}
}
private:
Logger() : active_(true), queues_size_(1), queue_size_(1024), cout_(true) {
thread_ = std::thread([this] { Writer(); });
}
~Logger() {
active_ = false;
if (thread_.joinable()) {
thread_.join();
}
}
Logger(Logger &other) = delete;
Logger &operator=(const Logger &) = delete;
Logger(Logger &&other) = delete;
Logger &operator=(Logger &&) = delete;
void Writer() {
using namespace std::chrono_literals;
while (active_ || queues_size_) {
{
std::lock_guard<std::mutex> lock(instance().mutex_);
for (auto it = queues_.begin(); it != queues_.end();) {
auto &q = *it;
while (q->front()) {
if (ostream_) {
q->front()->Format(*ostream_);
}
if (cout_) {
q->front()->Format(std::cout);
}
q->pop();
}
if (q.unique() && !q->front()) {
it = queues_.erase(it);
} else {
++it;
}
}
queues_size_ = queues_.size();
}
// std::this_thread::sleep_for(100ms);
}
}
static Logger &instance() {
static Logger instance;
return instance;
}
using QueueType = Queue<Message>;
static QueueType &queue() {
static thread_local std::shared_ptr<QueueType> queue;
if (queue == nullptr) {
queue = std::make_shared<QueueType>(instance().queue_size_);
std::lock_guard<std::mutex> lock(instance().mutex_);
instance().queues_.push_back(queue);
}
return *queue;
}
std::mutex mutex_;
std::vector<std::shared_ptr<QueueType>> queues_;
std::thread thread_;
bool active_;
size_t queues_size_;
size_t queue_size_;
bool cout_;
std::unique_ptr<std::ostream> ostream_;
};