Skip to content

Instantly share code, notes, and snippets.

@oschaaf
Created August 29, 2020 18:36
Show Gist options
  • Save oschaaf/4113ac357d7537a470c09c1f2285d731 to your computer and use it in GitHub Desktop.
Save oschaaf/4113ac357d7537a470c09c1f2285d731 to your computer and use it in GitHub Desktop.
envoy log macros
// use "clang -lstdc++ xxx.cc && ./a.out" to run & test
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;
#define ENVOY_LOG(...) std::cerr << "logline" << std::endl;
#define ENVOY_LOG_FIRST_N(LEVEL, N, ...) \
do { \
static std::atomic<uint64_t>* countdown = new std::atomic<uint64_t>(N); \
if (countdown->fetch_sub(1) > 0) { \
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
} \
} while (0)
#define ENVOY_LOG_ONCE(LEVEL, ...) ENVOY_LOG_FIRST_N(LEVEL, 1, ##__VA_ARGS__)
#define ENVOY_LOG_EVERY_NTH(LEVEL, N, ...) \
do { \
static std::atomic<uint64_t>* count = new std::atomic<uint64_t>(1); \
if ((count->fetch_add(1) % N) == 0) { \
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
} \
} while (0)
#define ENVOY_LOG_PERIODIC(LEVEL, CHRONO_DURATION, ...) \
do { \
static std::atomic<std::chrono::steady_clock::time_point>* last_hit = \
new std::atomic<std::chrono::steady_clock::time_point>(); \
auto last = last_hit->load(); \
const auto now = std::chrono::steady_clock::now(); \
if ((now - last) > CHRONO_DURATION && last_hit->compare_exchange_strong(last, now)) { \
ENVOY_LOG(LEVEL, ##__VA_ARGS__); \
} \
} while (0)
int main() {
int i = 0;
std::cerr << "expect four" << std::endl;
while (i++ < 100) {
ENVOY_LOG_FIRST_N("1", 2, "foo");
ENVOY_LOG_FIRST_N("2", 2, "foo");
}
i = 0;
std::cerr << "expect 8" << std::endl;
while (i++ < 40) {
ENVOY_LOG_EVERY_NTH("1", 10, "foo");
ENVOY_LOG_EVERY_NTH("2", 10, "foo");
}
i = 0;
std::cerr << "expect 6" << std::endl;
while (i++ < 200) {
ENVOY_LOG_PERIODIC("1", 0.1s, "foo");
ENVOY_LOG_PERIODIC("2", 0.1s, "foo");
usleep(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment