Enable Boost.Log only on debug

霸气de小男生 提交于 2019-12-04 08:01:38

The severity level of the log entry meerly acts as a filter for sinks. The sink will decide what to do with the message (print it or not) based on the severity level. But the message will still be sent.

If you are trying to not send the message at all, then you'll need to redefine LOG_MESSAGE to something which actually does nothing. there might be something in the Boost library for this, otherwise, you'll have to write your own. Perhaps this will be a start:

class NullLogger
{
public:
  template <typename SeverityT> NullLogger (SeverityT) {};
  template <typename Val> NullLog& operator<< (const Val&) { return * this};
};

...and then:

#define LOG_MESSAGE (lvl) NullLogger (lvl)

Note however that even though nothing is being done with the log message or the expressions that make it up, the expressions are still evaluated. If some of these expressions are expensive, you will still take the performance hit. For example:

LOG_MESSAGE (debug) << SomeSuperExpensiveFunction();

Even if you are using the NullLogger above, SomeSuperExpensiveFunction() is still going to be called.

I would suggest as an alternative adding a flag that is evaluated at runtime, and decide at runtime whether or not to do the logging:

if (mLogStuff)
{ 
  LOG_MESSAGE (debug) << SomeSuperExpensiveFunction();
}

boolean comparisons are super cheap, and you may find one day in the future that the ability to turn logging on and off could be super handy. Also, doing this means you don't need to add yet another #define, which is always a good thing.

I like John's NullLogger class. The only change I would make is as follows

#define LOG_MESSAGE(lvl) while (0) NullLogger (lvl)

Unfortunately this may generate warnings, but I would hope a decent compiler would then be able to eliminate all the associated logging code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!