c ++ logging - 如何为不执行任何操作的插入操作符编写条件宏

时间:2017-08-18 17:54:19

标签: c++ macros

我有一段使用plog进行日志记录的代码,如下所示:

int main(int argc, char** argv) {

  static plog::ColorConsoleAppender<plog::TxtFormatter> consoleAppender;
  plog::init(plog::verbose, &consoleAppender);

  // Log severity levels are printed in different colors.
  LOG_VERBOSE << "This is a VERBOSE message";
  LOG_DEBUG << "This is a DEBUG message";
  LOG_INFO << "This is an INFO message";
  LOG_WARNING << "This is a WARNING message";
  LOG_ERROR << "This is an ERROR message";
  LOG_FATAL << "This is a FATAL message";

  return 0;

}

由于此代码将成为库的一部分,因此除非正在使用它的应用程序启用,否则我不想发出任何日志。所以,我试图看看,如果我可以通过一些宏定义使上述日志记录代码无效。我尝试了以下操作,但导致编译错误:

#ifdef NO_LOGGING
#undef LOG_VERBOSE 
#define LOG_VERBOSE {}
#undef LOG_DEBUG 
#define LOG_DEBUG {}
#undef LOG_INFO 
#define LOG_INFO {}
#undef LOG_WARNING 
#define LOG_WARNING {}
#undef LOG_ERROR 
#define LOG_ERROR {}
#undef LOG_FATAL 
#define LOG_FATAL {}
#endif

这会导致编译错误

log_test.cpp:25:15: error: expected expression   LOG_VERBOSE << "This is a VERBOSE message" ;
              ^ log_test.cpp:26:13: error: expected expression   LOG_DEBUG << "This is a DEBUG message";
            ^ log_test.cpp:27:12: error: expected expression   LOG_INFO << "This is an INFO message";
           ^ log_test.cpp:28:15: error: expected expression   LOG_WARNING << "This is a WARNING message";
              ^ log_test.cpp:29:13: error: expected expression   LOG_ERROR << "This is an ERROR message";
            ^ log_test.cpp:30:13: error: expected expression   LOG_FATAL << "This is a FATAL message";
            ^

有没有办法解决这个问题并正确禁用日志?

2 个答案:

答案 0 :(得分:5)

你最好的选择是做这样的事情:

struct black_hole_t
{
    template <typename T> black_hole_t operator<<(T &&)
    {
        return {};
    }
};

black_hole_t black_hole;

#define LOG_BLAH black_hole

// or #define LOG_BLAH black_hole_t{}
// But GCC generates 1 more instruction for it at -O0,
// which hurts my inner love for premature optimizations.

希望您的编译器将其优化为无操作。

GCC 7.2与-O1禁止使用,clang 4.0至少需要-O2

答案 1 :(得分:2)

这是另一种可能的解决方案。

#ifdef NO_LOGGING

struct EmptyLog {};

template <typename T>
EmptyLog& operator<<(EmptyLog& e, T)
{
   return e;
}

EmptyLog& NoLog()
{
   static EmptyLog e;
   return e;
}

#undef LOG_VERBOSE 
#define LOG_VERBOSE NoLog()
#undef LOG_DEBUG 
#define LOG_DEBUG NoLog()
#undef LOG_INFO 
#define LOG_INFO NoLog()
#undef LOG_WARNING 
#define LOG_WARNING NoLog()
#undef LOG_ERROR 
#define LOG_ERROR NoLog()
#undef LOG_FATAL 
#define LOG_FATAL NoLog()

#endif

int main(int argc, char** argv) {

  // Log severity levels are printed in different colors.
  LOG_VERBOSE << "This is a VERBOSE message";
  LOG_DEBUG << "This is a DEBUG message";
  LOG_INFO << "This is an INFO message";
  LOG_WARNING << "This is a WARNING message";
  LOG_ERROR << "This is an ERROR message";
  LOG_FATAL << "This is a FATAL message";

  return 0;
}

请注意,它允许对消息进行排序。您可以使用:

  LOG_FATAL << "Unable to find login information for user\"" << user << "\".";