Skip to content

Commit 2d47780

Browse files
committed
Add ENVOY_LOG_FIRST_N, ENVOY_LOG_EVERY_NTH, ENVOY_LOG_PERIODIC
Periodic isn't perfect, as it reference a real-world time source directly. Depending on feedback / if it's a lot of work to do this right, it can be backed out for now. Will need a follow up with more tests for the new macros. Signed-off-by: Otto van der Schaaf <[email protected]>
1 parent 9e29f4a commit 2d47780

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

source/common/common/logger.h

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22

3+
#include <chrono>
34
#include <cstdint>
45
#include <memory>
56
#include <string>
@@ -400,11 +401,34 @@ template <Id id> class Loggable {
400401
} \
401402
} while (0)
402403

403-
#define ENVOY_LOG_ONCE(LEVEL, ...) \
404+
#define ENVOY_LOG_FIRST_N(LEVEL, N, ...) \
404405
do { \
405-
static std::atomic<bool>* logged = new std::atomic<bool>(false); \
406-
bool expected = false; \
407-
if (logged->compare_exchange_strong(expected /*expected value*/, true /*new value*/)) { \
406+
static auto* countdown = new std::atomic<uint64_t>(N); \
407+
if (countdown->fetch_sub(1) > 0) { \
408+
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
409+
} \
410+
} while (0)
411+
412+
#define ENVOY_LOG_ONCE(LEVEL, ...) ENVOY_LOG_FIRST_N(LEVEL, 1, ##__VA_ARGS__)
413+
414+
#define ENVOY_LOG_EVERY_NTH(LEVEL, N, ...) \
415+
do { \
416+
static auto* count = new std::atomic<uint64_t>(1); \
417+
if ((count->fetch_add(1) % N) == 0) { \
418+
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
419+
} \
420+
} while (0)
421+
422+
// This is to get us to pass the format check. We reference a real-world time source here.
423+
// I think it's not easy to mock/simulate time here as it stands today anyway.
424+
using t_logclock = std::chrono::steady_clock; // NOLINT
425+
426+
#define ENVOY_LOG_PERIODIC(LEVEL, CHRONO_DURATION, ...) \
427+
do { \
428+
static auto* last_hit = new std::atomic<t_logclock::time_point>(); \
429+
auto last = last_hit->load(); \
430+
const auto now = t_logclock::now(); \
431+
if ((now - last) > CHRONO_DURATION && last_hit->compare_exchange_strong(last, now)) { \
408432
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
409433
} \
410434
} while (0)

0 commit comments

Comments
 (0)