-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_logger.cpp
More file actions
835 lines (730 loc) · 27.8 KB
/
Copy pathasync_logger.cpp
File metadata and controls
835 lines (730 loc) · 27.8 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
#include "DetourModKit/async_logger.hpp"
#include "DetourModKit/diagnostics.hpp"
#include "platform.hpp"
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <new>
#include <sstream>
#include <type_traits>
namespace DetourModKit
{
using detail::is_loader_lock_held;
using detail::pin_current_module;
StringPool::StringPool() noexcept
{
std::lock_guard<std::mutex> lock(m_pool_mutex);
grow_pool_locked();
}
StringPool::~StringPool() noexcept
{
size_t leaked = 0;
{
// Acquire the mutex to synchronize with any in-flight deallocate() calls
std::lock_guard<std::mutex> lock(m_pool_mutex);
leaked = m_heap_fallback_count.load(std::memory_order_relaxed);
}
if (leaked > 0)
{
std::cerr << "[StringPool] " << leaked
<< " heap-fallback string(s) were not returned before destruction\n";
}
Block *current = m_head.load(std::memory_order_relaxed);
while (current)
{
Block *next = current->next;
PoolSlot *slots = reinterpret_cast<PoolSlot *>(current->data);
for (size_t i = 0; i < POOL_SLOTS_PER_BLOCK; ++i)
{
if (current->constructed_mask & (1u << i))
{
slots[i].~PoolSlot();
}
}
// Block is over-aligned (alignas(64)); it must be released through
// the aligned operator delete that matches its aligned allocation
// in grow_pool_locked().
::operator delete(current, std::align_val_t{alignof(Block)});
current = next;
}
m_head.store(nullptr, std::memory_order_relaxed);
}
void StringPool::grow_pool_locked() noexcept
{
Block *existing = m_head.load(std::memory_order_relaxed);
size_t count = 0;
for (Block *b = existing; b; b = b->next)
{
if (++count >= MEMORY_POOL_BLOCK_COUNT)
{
return;
}
}
// Block is over-aligned via its alignas(64) data member, so it must be
// allocated through the aligned operator new; the plain overload is not
// required to honour an alignment stricter than
// __STDCPP_DEFAULT_NEW_ALIGNMENT__ (typically 16 on x64), which would be
// alignment UB. The allocation is also nothrow: this runs underneath the
// noexcept logging path, so on out-of-memory it must leave the pool
// unchanged and let the caller fall back to a nothrow heap string (or
// drop the message) rather than let std::bad_alloc escape and terminate.
void *raw = ::operator new(sizeof(Block), std::align_val_t{alignof(Block)}, std::nothrow);
if (!raw)
{
return;
}
Block *new_block = new (raw) Block();
new_block->next = existing;
new_block->free_list = nullptr;
PoolSlot *slots = reinterpret_cast<PoolSlot *>(new_block->data);
static_assert(POOL_SLOTS_PER_BLOCK <= 32, "constructed_mask is uint32_t; increase its width if POOL_SLOTS_PER_BLOCK > 32");
// Slot construction must not throw, otherwise a partially built block
// could leak with no unwinding under this noexcept function. std::string's
// default constructor is noexcept, so the loop below is provably no-throw.
static_assert(std::is_nothrow_default_constructible_v<PoolSlot>,
"PoolSlot must be nothrow-default-constructible so grow_pool_locked stays no-throw");
uint32_t constructed = 0;
for (size_t i = 0; i < POOL_SLOTS_PER_BLOCK; ++i)
{
new (&slots[i]) PoolSlot();
constructed |= (1u << i);
slots[i].next_free = (i + 1 < POOL_SLOTS_PER_BLOCK) ? &slots[i + 1] : nullptr;
}
new_block->constructed_mask = constructed;
new_block->free_list = &slots[0];
m_head.store(new_block, std::memory_order_release);
}
StringPool &StringPool::instance() noexcept
{
// Constructed once into function-local static storage and never
// destroyed. A Meyers singleton would be destroyed at static teardown
// and race late LogMessage destructors that call into deallocate()
// (use-after-free under DLL unload and loader-lock teardown). A
// heap-allocated singleton (`*new StringPool()`) would instead require
// a throwing operator new whose std::bad_alloc would escape this
// noexcept accessor and terminate the host. Placement-new into static
// storage avoids both: the object lives for the whole process, its
// destructor never runs, and construction performs no throwing
// allocation because grow_pool_locked() is nothrow. The bounded block
// leak (at most MEMORY_POOL_BLOCK_COUNT blocks of
// MEMORY_POOL_BLOCK_SIZE bytes) is released by the OS at process exit.
alignas(StringPool) static unsigned char storage[sizeof(StringPool)];
static StringPool *const pool = ::new (static_cast<void *>(storage)) StringPool();
return *pool;
}
StringPool::PoolSlot *StringPool::claim_free_slot() noexcept
{
for (Block *b = m_head.load(std::memory_order_relaxed); b; b = b->next)
{
if (b->free_list)
{
PoolSlot *slot = b->free_list;
b->free_list = slot->next_free;
return slot;
}
}
return nullptr;
}
std::string *StringPool::allocate(size_t size) noexcept
{
if (size > MEMORY_POOL_BLOCK_SIZE - sizeof(PoolSlot) - 16)
{
auto *ptr = new (std::nothrow) std::string();
if (ptr)
{
m_heap_fallback_count.fetch_add(1, std::memory_order_relaxed);
}
return ptr;
}
std::lock_guard<std::mutex> lock(m_pool_mutex);
PoolSlot *slot = claim_free_slot();
if (!slot)
{
grow_pool_locked();
slot = claim_free_slot();
}
if (slot)
{
slot->str.clear();
return &slot->str;
}
auto *ptr = new (std::nothrow) std::string();
if (ptr)
{
m_heap_fallback_count.fetch_add(1, std::memory_order_relaxed);
}
return ptr;
}
void StringPool::deallocate(std::string *ptr) noexcept
{
if (!ptr)
return;
std::lock_guard<std::mutex> lock(m_pool_mutex);
for (Block *b = m_head.load(std::memory_order_relaxed); b; b = b->next)
{
const auto *block_begin = reinterpret_cast<const char *>(b->data);
const auto *block_end = block_begin + POOL_SLOTS_PER_BLOCK * sizeof(PoolSlot);
const auto *raw_ptr = reinterpret_cast<const char *>(ptr);
if (raw_ptr >= block_begin && raw_ptr < block_end)
{
auto offset = static_cast<size_t>(raw_ptr - block_begin);
PoolSlot *slot = reinterpret_cast<PoolSlot *>(b->data) + (offset / sizeof(PoolSlot));
slot->str.clear();
return_slot_locked(slot, b);
return;
}
}
// Not a pool allocation -- heap fallback. The delete is performed
// under m_pool_mutex to serialize with concurrent deallocate() calls
// that walk the block list above. Without the lock, a concurrent
// deallocate could see a partially updated free list. The lock does
// not prevent double-free of heap pointers (those are not tracked);
// callers must ensure each pointer is deallocated exactly once. The
// cost is a single free() call (or no-op for SSO-sized strings).
delete ptr;
if (m_heap_fallback_count.load(std::memory_order_relaxed) > 0)
{
m_heap_fallback_count.fetch_sub(1, std::memory_order_relaxed);
}
}
void StringPool::return_slot_locked(PoolSlot *slot, Block *block) noexcept
{
slot->next_free = block->free_list;
block->free_list = slot;
}
LogMessage::LogMessage(LogLevel lvl, std::string_view msg) noexcept
: level(lvl),
timestamp(std::chrono::system_clock::now()),
thread_id(std::this_thread::get_id())
{
const size_t msg_size = std::min(msg.size(), MAX_VALID_LENGTH);
if (msg_size <= MAX_INLINE_SIZE)
{
std::memcpy(buffer.data(), msg.data(), msg_size);
length = msg_size;
}
else
{
overflow = StringPool::instance().allocate(msg_size);
if (overflow)
{
try
{
overflow->assign(msg.data(), msg_size);
length = overflow->size();
}
catch (...)
{
StringPool::instance().deallocate(overflow);
overflow = nullptr;
length = 0;
}
}
else
{
// Allocation failed (OOM) -- message is silently dropped
length = 0;
}
}
}
LogMessage::~LogMessage() noexcept
{
reset();
}
// Move transfers ownership of the overflow pointer without touching the
// StringPool or m_heap_fallback_count. The allocation/deallocation balance
// is maintained because exactly one LogMessage owns the pointer at any
// time, and only reset() (called by the eventual owner's destructor)
// returns it to the pool.
LogMessage::LogMessage(LogMessage &&other) noexcept
: level(other.level),
timestamp(other.timestamp),
thread_id(other.thread_id),
length(other.length),
overflow(other.overflow)
{
if (length > 0 && !overflow)
{
std::memcpy(buffer.data(), other.buffer.data(), length);
}
other.overflow = nullptr;
other.length = 0;
}
LogMessage &LogMessage::operator=(LogMessage &&other) noexcept
{
if (this != &other)
{
reset();
level = other.level;
timestamp = other.timestamp;
thread_id = other.thread_id;
length = other.length;
overflow = other.overflow;
if (length > 0 && !overflow)
{
std::memcpy(buffer.data(), other.buffer.data(), length);
}
other.overflow = nullptr;
other.length = 0;
}
return *this;
}
std::string_view LogMessage::message() const noexcept
{
if (overflow)
{
return *overflow;
}
return std::string_view(buffer.data(), length);
}
bool LogMessage::is_valid() const noexcept
{
if (overflow)
{
return length == overflow->size();
}
return length <= MAX_INLINE_SIZE;
}
void LogMessage::reset() noexcept
{
if (overflow)
{
StringPool::instance().deallocate(overflow);
overflow = nullptr;
}
length = 0;
}
size_t DynamicMPMCQueue::validated_capacity(size_t capacity)
{
if ((capacity & (capacity - 1)) != 0 || capacity < 2)
{
throw std::invalid_argument("DynamicMPMCQueue capacity must be a power of 2 and at least 2");
}
return capacity;
}
DynamicMPMCQueue::DynamicMPMCQueue(size_t capacity)
: m_capacity(validated_capacity(capacity)), m_mask(m_capacity - 1),
m_buffer(std::make_unique<Slot[]>(m_capacity))
{
for (size_t i = 0; i < m_capacity; ++i)
{
m_buffer[i].sequence.store(i, std::memory_order_relaxed);
}
}
bool DynamicMPMCQueue::try_push(LogMessage &item)
{
size_t pos = m_enqueue_pos.load(std::memory_order_relaxed);
for (;;)
{
Slot &slot = m_buffer[pos & m_mask];
size_t seq = slot.sequence.load(std::memory_order_acquire);
intptr_t diff = static_cast<intptr_t>(seq) - static_cast<intptr_t>(pos);
if (diff == 0)
{
if (m_enqueue_pos.compare_exchange_weak(pos, pos + 1,
std::memory_order_relaxed))
{
slot.data = std::move(item);
slot.sequence.store(pos + 1, std::memory_order_release);
return true;
}
}
else if (diff < 0)
{
return false;
}
else
{
pos = m_enqueue_pos.load(std::memory_order_relaxed);
}
}
}
bool DynamicMPMCQueue::try_pop(LogMessage &item)
{
size_t pos = m_dequeue_pos.load(std::memory_order_relaxed);
for (;;)
{
Slot &slot = m_buffer[pos & m_mask];
size_t seq = slot.sequence.load(std::memory_order_acquire);
intptr_t diff = static_cast<intptr_t>(seq) - static_cast<intptr_t>(pos + 1);
if (diff == 0)
{
if (m_dequeue_pos.compare_exchange_weak(pos, pos + 1,
std::memory_order_relaxed))
{
item = std::move(slot.data);
slot.sequence.store(pos + m_capacity, std::memory_order_release);
return true;
}
}
else if (diff < 0)
{
return false;
}
else
{
pos = m_dequeue_pos.load(std::memory_order_relaxed);
}
}
}
size_t DynamicMPMCQueue::try_pop_batch(std::vector<LogMessage> &items, size_t max_count)
{
if (max_count == 0)
{
return 0;
}
items.reserve(items.size() + max_count);
size_t count = 0;
LogMessage msg;
while (count < max_count && try_pop(msg))
{
items.push_back(std::move(msg));
++count;
}
return count;
}
size_t DynamicMPMCQueue::size() const noexcept
{
size_t enq = m_enqueue_pos.load(std::memory_order_relaxed);
size_t deq = m_dequeue_pos.load(std::memory_order_relaxed);
return (enq >= deq) ? (enq - deq) : 0;
}
bool DynamicMPMCQueue::empty() const noexcept
{
return size() == 0;
}
AsyncLogger::AsyncLogger(const AsyncLoggerConfig &config,
std::shared_ptr<WinFileStream> file_stream,
std::shared_ptr<std::mutex> log_mutex)
: m_queue(config.queue_capacity),
m_config(config),
m_file_stream(std::move(file_stream)),
m_log_mutex(std::move(log_mutex))
{
if (!m_config.validate())
{
throw std::invalid_argument("Invalid AsyncLoggerConfig");
}
if (!m_file_stream)
{
throw std::invalid_argument("file_stream cannot be null");
}
if (!m_log_mutex)
{
throw std::invalid_argument("log_mutex cannot be null");
}
m_running.store(true, std::memory_order_release);
m_writer_thread = std::jthread(&AsyncLogger::writer_thread_func, this);
}
AsyncLogger::~AsyncLogger() noexcept
{
shutdown();
}
bool AsyncLogger::enqueue(LogLevel level, std::string_view message) noexcept
{
if (m_shutdown_requested.load(std::memory_order_acquire))
{
std::lock_guard<std::mutex> lock(*m_log_mutex);
if (!m_file_stream->is_open() || !m_file_stream->good())
{
// Stream already closed or failed during teardown: the message cannot be
// delivered, so report the drop rather than a false success.
return false;
}
const auto now = std::chrono::system_clock::now();
const auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm_buf{};
#if defined(_WIN32) || defined(_MSC_VER)
localtime_s(&tm_buf, &time_t);
#else
localtime_r(&time_t, &tm_buf);
#endif
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) %
1000;
*m_file_stream << "[" << std::put_time(&tm_buf, m_config.timestamp_format.c_str())
<< "." << std::setfill('0') << std::setw(3) << ms.count()
<< std::setfill(' ') << "] "
<< "[" << std::setw(7) << std::left << log_level_to_string(level) << "] :: "
<< message << '\n';
m_file_stream->flush();
// Surface a write/flush failure through the no-throw delivery bool.
return m_file_stream->good();
}
LogMessage msg(level, message);
// Increment before push so flush cannot observe zero while a message
// is already in the queue but not yet counted.
m_pending_messages.fetch_add(1, std::memory_order_acq_rel);
if (m_queue.try_push(msg))
{
m_flush_cv.notify_one();
return true;
}
// Push failed -- undo the pre-increment before entering overflow handling
m_pending_messages.fetch_sub(1, std::memory_order_acq_rel);
return handle_overflow(std::move(msg));
}
bool AsyncLogger::flush_with_timeout(std::chrono::milliseconds timeout) noexcept
{
if (!m_running.load(std::memory_order_acquire))
{
return true;
}
std::unique_lock<std::mutex> lock(m_flush_mutex);
const bool flushed = m_flush_cv.wait_for(lock, timeout, [this]() noexcept
{ return m_pending_messages.load(std::memory_order_acquire) == 0; });
return flushed;
}
void AsyncLogger::flush() noexcept
{
static_cast<void>(flush_with_timeout(DEFAULT_FLUSH_TIMEOUT));
}
void AsyncLogger::shutdown() noexcept
{
bool expected = false;
if (!m_shutdown_requested.compare_exchange_strong(expected, true,
std::memory_order_acq_rel))
{
return;
}
m_running.store(false, std::memory_order_release);
m_flush_cv.notify_all();
if (m_writer_thread.joinable())
{
if (is_loader_lock_held())
{
pin_current_module();
m_writer_thread.detach();
DetourModKit::Diagnostics::record_intentional_leak(DetourModKit::Diagnostics::LeakSubsystem::AsyncLogger);
}
else
{
m_writer_thread.join();
}
}
// Drain any messages enqueued between m_running=false and the writer
// thread exiting. Without this, late-arriving messages would be silently
// lost and the force-zero below would mask the discrepancy.
//
// A narrow race remains: a producer that already passed the
// m_shutdown_requested check in enqueue() but has not yet called
// try_push() can enqueue one message after this drain completes.
// This is an accepted trade-off -- closing it would require a
// producers_in_flight atomic counter on every enqueue() call,
// adding two atomic RMW operations to the hot path. At most one
// message per producer thread can be lost, and only during the
// nanosecond window between the drain and the force-zero below.
drain_remaining();
{
std::lock_guard<std::mutex> lock(m_flush_mutex);
m_pending_messages.store(0, std::memory_order_release);
m_flush_cv.notify_all();
}
}
bool AsyncLogger::is_running() const noexcept
{
return m_running.load(std::memory_order_acquire);
}
size_t AsyncLogger::queue_size() const noexcept
{
return m_queue.size();
}
size_t AsyncLogger::dropped_count() const noexcept
{
return m_dropped_messages.load(std::memory_order_relaxed);
}
void AsyncLogger::reset_dropped_count() noexcept
{
m_dropped_messages.store(0, std::memory_order_release);
}
void AsyncLogger::writer_thread_func() noexcept
{
std::vector<LogMessage> batch;
batch.reserve(m_config.batch_size);
const auto start_time = std::chrono::steady_clock::now();
auto last_flush = start_time;
while (m_running.load(std::memory_order_acquire) || !m_queue.empty())
{
batch.clear();
m_queue.try_pop_batch(batch, m_config.batch_size);
if (!batch.empty())
{
write_batch(batch);
const size_t batch_size = batch.size();
{
std::lock_guard<std::mutex> flock(m_flush_mutex);
m_pending_messages.fetch_sub(batch_size, std::memory_order_acq_rel);
}
m_flush_cv.notify_all();
last_flush = std::chrono::steady_clock::now();
}
else
{
auto now = std::chrono::steady_clock::now();
if (now - last_flush >= m_config.flush_interval)
{
std::lock_guard<std::mutex> lock(*m_log_mutex);
if (m_file_stream->is_open())
{
m_file_stream->flush();
}
last_flush = now;
}
std::unique_lock<std::mutex> lock(m_flush_mutex);
m_flush_cv.wait_for(lock, m_config.flush_interval, [this]()
{ return !m_queue.empty() || !m_running.load(std::memory_order_acquire); });
}
}
{
std::lock_guard<std::mutex> lock(*m_log_mutex);
if (m_file_stream->is_open())
{
m_file_stream->flush();
}
}
{
std::lock_guard<std::mutex> lock(m_flush_mutex);
m_pending_messages.store(0, std::memory_order_release);
m_flush_cv.notify_all();
}
}
void AsyncLogger::drain_remaining() noexcept
{
std::vector<LogMessage> remaining;
remaining.reserve(m_config.batch_size);
while (m_queue.try_pop_batch(remaining, m_config.batch_size) > 0)
{
write_batch(remaining);
remaining.clear();
}
}
void AsyncLogger::write_batch(std::span<LogMessage> messages) noexcept
{
std::lock_guard<std::mutex> lock(*m_log_mutex);
if (!m_file_stream->is_open() || !m_file_stream->good())
{
return;
}
// Cache the localtime result across consecutive messages that share the
// same second to avoid repeated CRT lock acquisition inside localtime_s.
std::time_t cached_second{-1};
std::tm cached_tm{};
for (const auto &msg : messages)
{
const auto time_t = std::chrono::system_clock::to_time_t(msg.timestamp);
if (time_t != cached_second)
{
cached_second = time_t;
#if defined(_WIN32) || defined(_MSC_VER)
localtime_s(&cached_tm, &time_t);
#else
localtime_r(&time_t, &cached_tm);
#endif
}
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
msg.timestamp.time_since_epoch()) %
1000;
*m_file_stream << "[" << std::put_time(&cached_tm, m_config.timestamp_format.c_str())
<< "." << std::setfill('0') << std::setw(3) << ms.count()
<< std::setfill(' ') << "] "
<< "[" << std::setw(7) << std::left << log_level_to_string(msg.level) << "] :: "
<< msg.message() << '\n';
}
m_file_stream->flush();
}
bool AsyncLogger::handle_overflow(LogMessage &&message) noexcept
{
switch (m_config.overflow_policy)
{
case OverflowPolicy::DropNewest:
m_dropped_messages.fetch_add(1, std::memory_order_relaxed);
return false;
case OverflowPolicy::DropOldest:
{
LogMessage oldest;
if (m_queue.try_pop(oldest))
{
// Count the evicted oldest message as dropped
m_dropped_messages.fetch_add(1, std::memory_order_relaxed);
if (m_queue.try_push(message))
{
// Net effect on m_pending_messages: pop(-1) + push(+1) = 0
m_flush_cv.notify_one();
return true;
}
// Pop succeeded but push failed: net -1
m_pending_messages.fetch_sub(1, std::memory_order_acq_rel);
}
// Count the new message as dropped (separate from the evicted oldest above).
// m_dropped_messages counts individual lost messages, not overflow events.
m_dropped_messages.fetch_add(1, std::memory_order_relaxed);
return false;
}
case OverflowPolicy::Block:
{
const auto deadline = std::chrono::steady_clock::now() + m_config.block_timeout_ms;
size_t spin_count = 0;
// Pre-increment so flush sees the in-flight message throughout the retry loop
m_pending_messages.fetch_add(1, std::memory_order_acq_rel);
while (std::chrono::steady_clock::now() < deadline)
{
if (m_queue.try_push(message))
{
m_flush_cv.notify_one();
return true;
}
if (spin_count < m_config.spin_backoff_iterations)
{
++spin_count;
}
else if (spin_count < m_config.block_max_spin_iterations)
{
std::this_thread::yield();
++spin_count;
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
// Timed out -- undo the pre-increment
m_pending_messages.fetch_sub(1, std::memory_order_acq_rel);
m_dropped_messages.fetch_add(1, std::memory_order_relaxed);
return false;
}
case OverflowPolicy::SyncFallback:
{
std::lock_guard<std::mutex> lock(*m_log_mutex);
if (!m_file_stream->is_open() || !m_file_stream->good())
{
return false;
}
const auto time_t = std::chrono::system_clock::to_time_t(message.timestamp);
std::tm tm_buf{};
#if defined(_WIN32) || defined(_MSC_VER)
localtime_s(&tm_buf, &time_t);
#else
localtime_r(&time_t, &tm_buf);
#endif
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
message.timestamp.time_since_epoch()) %
1000;
*m_file_stream << "[" << std::put_time(&tm_buf, m_config.timestamp_format.c_str())
<< "." << std::setfill('0') << std::setw(3) << ms.count()
<< std::setfill(' ') << "] "
<< "[" << std::setw(7) << std::left << log_level_to_string(message.level) << "] :: "
<< message.message() << '\n';
m_file_stream->flush();
if (m_file_stream->fail())
{
return false;
}
return true;
}
default:
m_dropped_messages.fetch_add(1, std::memory_order_relaxed);
return false;
}
}
} // namespace DetourModKit