1010#define GC_LOG_H
1111#include < iostream>
1212
13+ #ifndef NDEBUG
14+ #include < regex>
15+ #endif
16+
1317namespace mlir ::gc::log {
1418static void insertArgs (std::ostream &stream) { stream << std::endl; }
1519
@@ -20,7 +24,7 @@ static void insertArgs(std::ostream &stream, T first, Args... args) {
2024}
2125
2226template <typename ... Args>
23- static void insetLog (
27+ static void log (
2428#ifndef NDEBUG
2529 const char *fileName, int lineNum,
2630#endif
@@ -36,16 +40,35 @@ static void insetLog(
3640#define gcLogD (...)
3741#define gcLogE (...) mlir::gc::log::insetLog(std::cerr, " ERROR" , __VA_ARGS__)
3842#else
39- #define _insetLog (stream, pref, ...) \
40- mlir::gc::log::insetLog (__FILE__, __LINE__, stream, pref, __VA_ARGS__)
41- #define gcLogD (...) _insetLog(std::cout, " DEBUG" , __VA_ARGS__)
42- #define gcLogE (...) _insetLog(std::cerr, " ERROR" , __VA_ARGS__)
43- #endif
44- } // namespace mlir::gc::log
4543
46- #ifdef GC_LOG_NO_DEBUG
47- #undef gcLogD
48- #define gcLogD (...)
44+ // The debug logs are enabled by setting the environment variable GC_DEBUG to a
45+ // regex pattern. The pattern is matched against the file name where the log is
46+ // called. Examples:
47+ // GC_DEBUG=.* - Enable all debug logs.
48+ // GC_DEBUG=/(CPU|GPU)Runtime/ - Enable debug logs in files containing
49+ // CPURuntime or GPURuntime in the path.
50+ static bool isDebugEnabled (const char *fileName) {
51+ static std::regex pattern = []() {
52+ auto env = std::getenv (" GC_DEBUG" );
53+ return env ? std::regex (env, std::regex::extended)
54+ : std::regex (" " , std::regex::basic);
55+ }();
56+ // The flag 'basic' is used as a marker for an empty regex.
57+ return pattern.flags () != std::regex::basic &&
58+ std::regex_search (fileName, pattern);
59+ }
60+
61+ template <typename ... Args>
62+ static void debug (const char *fileName, int lineNum, Args... args) {
63+ if (isDebugEnabled (fileName)) {
64+ log (fileName, lineNum, std::cout, " DEBUG" , args...);
65+ }
66+ }
67+
68+ #define gcLogD (...) mlir::gc::log::debug(__FILE__, __LINE__, __VA_ARGS__)
69+ #define gcLogE (...) \
70+ mlir::gc::log::log (__FILE__, __LINE__, std::cerr, " ERROR" , __VA_ARGS__)
4971#endif
72+ } // namespace mlir::gc::log
5073
5174#endif
0 commit comments