Repository navigation
Expand file tree
/
Copy pathAsyncLog.hpp
More file actions
416 lines (371 loc) · 15 KB
/
Copy pathAsyncLog.hpp
File metadata and controls
416 lines (371 loc) · 15 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#pragma once
#include "prx/libc/include/Shutdown.hpp"
#include "prx/libc/include/general/LogMacros.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <initializer_list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace AgcDriver {
struct LogLiteral {
const char* text;
};
namespace AsyncLogDetail {
template<typename T>
inline constexpr bool Deferrable = std::is_arithmetic_v<T> || std::is_enum_v<T> || std::is_same_v<T, LogLiteral>;
inline const char* Unwrap(LogLiteral value) {
return value.text;
}
template<typename T>
T Unwrap(T value) {
return value;
}
class Formatter {
public:
virtual ~Formatter() = default;
virtual void Format(std::string& out) const = 0;
};
template<typename... TArgs>
class Bound final : public Formatter {
public:
Bound(const char* format, TArgs... args) : format(format), values(args...) {}
void Format(std::string& out) const override {
std::apply([&](const auto&... value) { Append(out, value...); }, values);
}
private:
void Append(std::string& out, const auto&... value) const {
char small[512];
const int size = std::snprintf(small, sizeof(small), format, Unwrap(value)...);
if (size < 0) return;
if (static_cast<std::size_t>(size) < sizeof(small)) {
out.append(small, static_cast<std::size_t>(size));
return;
}
std::string large(static_cast<std::size_t>(size) + 1, '\0');
std::snprintf(large.data(), large.size(), format, Unwrap(value)...);
out.append(large.data(), static_cast<std::size_t>(size));
}
const char* format;
std::tuple<TArgs...> values;
};
struct Entry {
std::FILE* stream = nullptr;
long long micros = -1;
std::string text;
std::unique_ptr<Formatter> deferred;
std::size_t cost = 0;
};
}
class AsyncLog {
public:
using Clock = std::chrono::steady_clock;
static constexpr std::size_t Capacity = 16u * 1024u * 1024u;
static AsyncLog& Get() {
static AsyncLog* const instance = new AsyncLog();
return *instance;
}
int Write(std::FILE* stream, const char* text, std::size_t length) {
const auto start = Clock::now();
if (!asynchronous) return WriteNow(stream, text, length);
AsyncLogDetail::Entry entry;
entry.stream = stream;
entry.text.assign(text, length);
entry.cost = sizeof(entry) + length;
Enqueue(std::move(entry));
callerNanoseconds.fetch_add(Elapsed(start), std::memory_order_relaxed);
return 0;
}
template<typename... TArgs>
void Defer(std::FILE* stream, const char* format, TArgs... args) {
static_assert((AsyncLogDetail::Deferrable<TArgs> && ...), "deferred log arguments are numbers, enums or LogLiteral");
const auto start = Clock::now();
const auto micros = LogTimestampMicros();
auto bound = std::make_unique<AsyncLogDetail::Bound<TArgs...>>(format, args...);
if (!asynchronous) {
std::string text;
if (micros >= 0) AppendTimestamp(text, micros);
bound->Format(text);
WriteNow(stream, text.data(), text.size());
return;
}
AsyncLogDetail::Entry entry;
entry.stream = stream;
entry.micros = micros;
entry.deferred = std::move(bound);
entry.cost = sizeof(entry) + sizeof(AsyncLogDetail::Bound<TArgs...>);
Enqueue(std::move(entry));
callerNanoseconds.fetch_add(Elapsed(start), std::memory_order_relaxed);
}
bool Admit(const std::string& line) {
const auto now = Clock::now();
std::string summary;
{
std::lock_guard lock(coalesceMutex);
auto found = windows.find(line);
if (found == windows.end()) {
if (windows.size() >= CoalesceKeys) return true;
windows.emplace(line, Window{now, 1, 0});
return true;
}
auto& window = found->second;
if (now - window.first < CoalesceWindow) {
if (++window.seen <= PrintedRepeats) return true;
++window.suppressed;
coalescedTotal.fetch_add(1, std::memory_order_relaxed);
return false;
}
summary = Summary(found->first, window.suppressed);
window = Window{now, 1, 0};
}
if (!summary.empty()) WriteNow(stderr, summary.data(), summary.size());
return true;
}
void Flush() {
if (!asynchronous) return;
std::unique_lock lock(mutex);
const auto target = queued.load(std::memory_order_relaxed);
idle.wait(lock, [&] { return finished.load(std::memory_order_relaxed) >= target; });
}
bool FlushFor(std::chrono::milliseconds limit) {
if (!asynchronous) return true;
const auto target = queued.load(std::memory_order_acquire);
const auto deadline = Clock::now() + limit;
while (finished.load(std::memory_order_acquire) < target) {
if (Clock::now() >= deadline) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return true;
}
static void FlushAtEnd() {
auto& log = Get();
if (log.abandoned.load(std::memory_order_acquire)) return;
if (!log.FlushFor(EndFlushLimit)) log.abandoned.store(true, std::memory_order_release);
}
std::unique_lock<std::mutex> Hold() {
return std::unique_lock(mutex);
}
private:
struct Window {
Clock::time_point first;
std::uint64_t seen;
std::uint64_t suppressed;
};
static constexpr std::size_t CoalesceKeys = 128;
static constexpr std::uint64_t PrintedRepeats = 3;
static constexpr std::chrono::seconds CoalesceWindow{10};
static constexpr std::chrono::seconds StatsWindow{10};
static constexpr std::chrono::milliseconds Tick{500};
static constexpr std::chrono::milliseconds EndFlushLimit{2000};
AsyncLog() {
asynchronous = std::getenv("APS5_LOG_SYNC") == nullptr;
const char* stats = std::getenv("APS5_LOG_STATS");
statsEnabled = stats == nullptr || std::string(stats) != "0";
lastStats = Clock::now();
if (!asynchronous) return;
LogSink().store(&AsyncLog::Sink, std::memory_order_release);
std::atexit(&AsyncLog::FlushAtEnd);
InitializeWaits();
std::thread([this] { Run(); }).detach();
LibcSetEndFlush_nid_no_patch(&AsyncLog::FlushAtEnd);
}
void InitializeWaits() {
std::unique_lock lock(mutex);
for (auto* condition : {&wake, &space, &idle}) static_cast<void>(condition->wait_for(lock, std::chrono::nanoseconds(0)));
}
static int Sink(std::FILE* stream, const char* text, std::size_t length) {
return Get().Write(stream, text, length);
}
static std::uint64_t Elapsed(Clock::time_point start) {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count());
}
static void AppendTimestamp(std::string& out, long long micros) {
char prefix[64];
const int size = FormatLogTimestamp(prefix, sizeof(prefix), micros);
if (size > 0) out.append(prefix, static_cast<std::size_t>(size));
}
static std::string Summary(const std::string& line, std::uint64_t suppressed) {
if (suppressed == 0) return {};
std::string text = line;
while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back();
text += " (repeated " + std::to_string(suppressed) + " more times in the last 10 s)\n";
return text;
}
static int WriteNow(std::FILE* stream, const char* text, std::size_t length) {
std::fwrite(text, 1, length, stream);
return std::fflush(stream);
}
void Enqueue(AsyncLogDetail::Entry&& entry) {
bool notify = false;
{
std::unique_lock lock(mutex);
space.wait(lock, [&] { return bytes == 0 || bytes + entry.cost <= Capacity; });
bytes += entry.cost;
peak = std::max(peak, bytes);
pending.push_back(std::move(entry));
queued.fetch_add(1, std::memory_order_release);
notify = sleeping;
sleeping = false;
}
if (notify) wake.notify_one();
}
void Run() noexcept {
std::deque<AsyncLogDetail::Entry> batch;
std::string buffer;
for (;;) {
{
std::unique_lock lock(mutex);
sleeping = true;
wake.wait_for(lock, Tick, [&] { return !pending.empty(); });
sleeping = false;
batch.swap(pending);
bytes = 0;
}
space.notify_all();
if (!batch.empty()) {
const auto start = Clock::now();
const auto count = batch.size();
try {
Drain(batch, buffer);
} catch (...) {
buffer.clear();
}
batch.clear();
loggerNanoseconds.fetch_add(Elapsed(start), std::memory_order_relaxed);
{
std::lock_guard lock(mutex);
finished.fetch_add(count, std::memory_order_release);
}
idle.notify_all();
}
try {
Housekeeping();
} catch (...) {
}
}
}
void Drain(std::deque<AsyncLogDetail::Entry>& batch, std::string& buffer) {
std::FILE* current = nullptr;
buffer.clear();
std::uint64_t outLines = 0;
std::uint64_t errLines = 0;
std::uint64_t written = 0;
const auto emit = [&] {
if (current != nullptr && !buffer.empty()) {
written += buffer.size();
WriteNow(current, buffer.data(), buffer.size());
}
buffer.clear();
};
for (auto& entry : batch) {
if (entry.stream != current) {
emit();
current = entry.stream;
}
if (entry.deferred) {
if (entry.micros >= 0) AppendTimestamp(buffer, entry.micros);
entry.deferred->Format(buffer);
} else {
buffer += entry.text;
}
(entry.stream == stderr ? errLines : outLines) += 1;
if (buffer.size() >= 65536) emit();
}
emit();
stdoutLines.fetch_add(outLines, std::memory_order_relaxed);
stderrLines.fetch_add(errLines, std::memory_order_relaxed);
loggedBytes.fetch_add(written, std::memory_order_relaxed);
}
void Housekeeping() {
const auto now = Clock::now();
std::vector<std::string> summaries;
{
std::lock_guard lock(coalesceMutex);
for (auto it = windows.begin(); it != windows.end();) {
if (now - it->second.first >= CoalesceWindow) {
const auto summary = Summary(it->first, it->second.suppressed);
if (!summary.empty()) summaries.push_back(summary);
it = windows.erase(it);
} else {
++it;
}
}
}
for (const auto& summary : summaries) WriteNow(stderr, summary.data(), summary.size());
if (now - lastStats < StatsWindow) return;
const double seconds = std::chrono::duration<double>(now - lastStats).count();
lastStats = now;
const auto outLines = stdoutLines.exchange(0, std::memory_order_relaxed);
const auto errLines = stderrLines.exchange(0, std::memory_order_relaxed);
const auto written = loggedBytes.exchange(0, std::memory_order_relaxed);
const auto caller = callerNanoseconds.exchange(0, std::memory_order_relaxed);
const auto logger = loggerNanoseconds.exchange(0, std::memory_order_relaxed);
const auto coalesced = coalescedTotal.exchange(0, std::memory_order_relaxed);
std::size_t high = 0;
{
std::lock_guard lock(mutex);
high = peak;
peak = bytes;
}
if (!statsEnabled || outLines + errLines + coalesced == 0) return;
char line[512];
const int size = std::snprintf(line, sizeof(line), "[log] %.1f s: %llu lines (%llu stdout, %llu stderr), %.1f KiB written, %llu repeats coalesced; callers spent %.2f ms queueing and formatting (%.3f%% of one thread), logger thread %.2f ms, queue peak %.1f KiB\n", seconds, static_cast<unsigned long long>(outLines + errLines), static_cast<unsigned long long>(outLines), static_cast<unsigned long long>(errLines), static_cast<double>(written) / 1024.0, static_cast<unsigned long long>(coalesced), static_cast<double>(caller) / 1e6, static_cast<double>(caller) / 1e9 / seconds * 100.0, static_cast<double>(logger) / 1e6, static_cast<double>(high) / 1024.0);
if (size > 0) WriteNow(stderr, line, std::min(static_cast<std::size_t>(size), sizeof(line) - 1));
}
bool asynchronous = true;
bool statsEnabled = true;
std::mutex mutex;
std::condition_variable wake;
std::condition_variable space;
std::condition_variable idle;
std::deque<AsyncLogDetail::Entry> pending;
std::size_t bytes = 0;
std::size_t peak = 0;
bool sleeping = false;
std::atomic<std::uint64_t> queued{0};
std::atomic<std::uint64_t> finished{0};
std::atomic<bool> abandoned{false};
std::mutex coalesceMutex;
std::map<std::string, Window> windows;
Clock::time_point lastStats;
std::atomic<std::uint64_t> stdoutLines{0};
std::atomic<std::uint64_t> stderrLines{0};
std::atomic<std::uint64_t> loggedBytes{0};
std::atomic<std::uint64_t> callerNanoseconds{0};
std::atomic<std::uint64_t> loggerNanoseconds{0};
std::atomic<std::uint64_t> coalescedTotal{0};
};
inline void InstallAsyncLog_nid_no_patch() {
static_cast<void>(AsyncLog::Get());
}
void FlushAsyncLog_nid_no_patch();
inline void FlushAsyncLogAtEnd_nid_no_patch() {
AsyncLog::FlushAtEnd();
}
std::unique_lock<std::mutex> HoldAsyncLog();
template<typename... TArgs>
void LogCoalescedStderr_nid_no_patch(const char* format, TArgs... args) {
char small[1024];
const int size = std::snprintf(small, sizeof(small), format, args...);
if (size < 0) return;
std::string line = static_cast<std::size_t>(size) < sizeof(small) ? std::string(small, static_cast<std::size_t>(size)) : std::string(static_cast<std::size_t>(size), '\0');
if (static_cast<std::size_t>(size) >= sizeof(small)) std::snprintf(line.data(), line.size() + 1, format, args...);
if (!AsyncLog::Get().Admit(line)) return;
std::fwrite(line.data(), 1, line.size(), stderr);
std::fflush(stderr);
}
}
#define AGC_LOG_DEFERRED(stream, fmt, ...) \
::AgcDriver::AsyncLog::Get().Defer(stream, "[%s:%d %s] " fmt "\n", ::AgcDriver::LogLiteral{_APS5_FILE_}, __LINE__, ::AgcDriver::LogLiteral{TrimNidPostfix(__func__)}, __VA_ARGS__)