From cf18fb707099d4c2e387dfcd4be859e1cf5d4855 Mon Sep 17 00:00:00 2001 From: Ke Wen Date: Fri, 12 Sep 2025 09:13:49 -0700 Subject: [PATCH] Add GLOO_LOG_LEVEL env --- gloo/common/logging.cc | 29 +++++++++++++++++++++++++++++ gloo/common/logging.h | 41 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/gloo/common/logging.cc b/gloo/common/logging.cc index 8d6daed59..d30994b0b 100644 --- a/gloo/common/logging.cc +++ b/gloo/common/logging.cc @@ -9,10 +9,39 @@ #include "gloo/common/logging.h" #include +#include #include namespace gloo { +// Initialize log level from environment variable, and return static value at +// each inquiry. +inline LogLevel logLevel() { + // Global log level. Initialized once. + static LogLevel log_level = LogLevel::UNSET; + if (log_level != LogLevel::UNSET) { + return log_level; + } + + const char* level = getenv("GLOO_LOG_LEVEL"); + // Defaults to WARN. + if (level == nullptr) { + log_level = LogLevel::WARN; + return log_level; + } + + if (std::strcmp(level, "DEBUG") == 0) { + log_level = LogLevel::DEBUG; + } else if (std::strcmp(level, "INFO") == 0) { + log_level = LogLevel::INFO; + } else if (std::strcmp(level, "WARN") == 0) { + log_level = LogLevel::WARN; + } else { + log_level = LogLevel::ERROR; + } + return log_level; +} + EnforceNotMet::EnforceNotMet( const char* file, const int line, diff --git a/gloo/common/logging.h b/gloo/common/logging.h index a678fdc87..32da6068f 100644 --- a/gloo/common/logging.h +++ b/gloo/common/logging.h @@ -20,14 +20,47 @@ namespace gloo { +enum LogLevel { + ERROR, + WARN, + INFO, + DEBUG, + UNSET, +}; + +inline LogLevel logLevel(); + #define GLOO_LOG_MSG(level, ...) \ std::cerr << ::gloo::MakeString( \ "[", __FILE__, ":", __LINE__, "] ", level, " ", __VA_ARGS__, "\n") -#define GLOO_INFO(...) GLOO_LOG_MSG("INFO", __VA_ARGS__) -#define GLOO_ERROR(...) GLOO_LOG_MSG("ERROR", __VA_ARGS__) -#define GLOO_WARN(...) GLOO_LOG_MSG("WARN", __VA_ARGS__) -#define GLOO_DEBUG(...) // GLOO_LOG_MSG("DEBUG", __VA_ARGS__) +#define GLOO_ERROR(...) \ + do { \ + if (logLevel() >= LogLevel::ERROR) { \ + GLOO_LOG_MSG("ERROR", __VA_ARGS__); \ + } \ + } while (0) + +#define GLOO_WARN(...) \ + do { \ + if (logLevel() >= LogLevel::WARN) { \ + GLOO_LOG_MSG("WARN", __VA_ARGS__); \ + } \ + } while (0) + +#define GLOO_INFO(...) \ + do { \ + if (logLevel() >= LogLevel::INFO) { \ + GLOO_LOG_MSG("INFO", __VA_ARGS__); \ + } \ + } while (0) + +#define GLOO_DEBUG(...) \ + do { \ + if (logLevel() >= LogLevel::DEBUG) { \ + GLOO_LOG_MSG("DEBUG", __VA_ARGS__); \ + } \ + } while (0) class EnforceNotMet : public std::exception { public: