Skip to content

Commit f46703b

Browse files
committed
Add GLOO_LOG_LEVEL env
1 parent 1b4337a commit f46703b

File tree

2 files changed

+66
-4
lines changed

2 files changed

+66
-4
lines changed

gloo/common/logging.cc

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,39 @@
99
#include "gloo/common/logging.h"
1010

1111
#include <algorithm>
12+
#include <cstring>
1213
#include <numeric>
1314

1415
namespace gloo {
1516

17+
// Initialize log level from environment variable, and return static value at
18+
// each inquiry.
19+
inline LogLevel logLevel() {
20+
// Global log level. Initialized once.
21+
static LogLevel log_level = LogLevel::UNSET;
22+
if (log_level != LogLevel::UNSET) {
23+
return log_level;
24+
}
25+
26+
const char* level = getenv("GLOO_LOG_LEVEL");
27+
// Defaults to ERROR.
28+
if (level == nullptr) {
29+
log_level = LogLevel::ERROR;
30+
return log_level;
31+
}
32+
33+
if (std::strcmp(level, "DEBUG") == 0) {
34+
log_level = LogLevel::DEBUG;
35+
} else if (std::strcmp(level, "INFO") == 0) {
36+
log_level = LogLevel::INFO;
37+
} else if (std::strcmp(level, "WARN") == 0) {
38+
log_level = LogLevel::WARN;
39+
} else {
40+
log_level = LogLevel::ERROR;
41+
}
42+
return log_level;
43+
}
44+
1645
EnforceNotMet::EnforceNotMet(
1746
const char* file,
1847
const int line,

gloo/common/logging.h

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,47 @@
2020

2121
namespace gloo {
2222

23+
enum LogLevel {
24+
ERROR,
25+
WARN,
26+
INFO,
27+
DEBUG,
28+
UNSET,
29+
};
30+
31+
inline LogLevel logLevel();
32+
2333
#define GLOO_LOG_MSG(level, ...) \
2434
std::cerr << ::gloo::MakeString( \
2535
"[", __FILE__, ":", __LINE__, "] ", level, " ", __VA_ARGS__, "\n")
2636

27-
#define GLOO_INFO(...) GLOO_LOG_MSG("INFO", __VA_ARGS__)
28-
#define GLOO_ERROR(...) GLOO_LOG_MSG("ERROR", __VA_ARGS__)
29-
#define GLOO_WARN(...) GLOO_LOG_MSG("WARN", __VA_ARGS__)
30-
#define GLOO_DEBUG(...) // GLOO_LOG_MSG("DEBUG", __VA_ARGS__)
37+
#define GLOO_ERROR(...) \
38+
do { \
39+
if (logLevel() >= LogLevel::ERROR) { \
40+
GLOO_LOG_MSG("ERROR", __VA_ARGS__); \
41+
} \
42+
} while (0)
43+
44+
#define GLOO_WARN(...) \
45+
do { \
46+
if (logLevel() >= LogLevel::WARN) { \
47+
GLOO_LOG_MSG("WARN", __VA_ARGS__); \
48+
} \
49+
} while (0)
50+
51+
#define GLOO_INFO(...) \
52+
do { \
53+
if (logLevel() >= LogLevel::INFO) { \
54+
GLOO_LOG_MSG("INFO", __VA_ARGS__); \
55+
} \
56+
} while (0)
57+
58+
#define GLOO_DEBUG(...) \
59+
do { \
60+
if (logLevel() >= LogLevel::DEBUG) { \
61+
GLOO_LOG_MSG("DEBUG", __VA_ARGS__); \
62+
} \
63+
} while (0)
3164

3265
class EnforceNotMet : public std::exception {
3366
public:

0 commit comments

Comments
 (0)