c++ - Enable Boost.Log only on debug -


i need logger debug purpose , i'm using boost.log (1.54.0 patch in boost.org homepage).

it's fine i've created macro this:

#define log_message( lvl ) boost_log_trivial( lvl ) 

now way log_message( lvl ) expaneded in boost_log_trivial( lvl ) in debug mode , ignore in release?

for example:

log_message( critical ) << "if read message we're in debug mode" 

edit first attempt create nullstream... think in release mode compiler optimize it...

#if !defined( ndebug ) #include <boost/log/trivial.hpp> #define log_message( lvl ) boost_log_trivial( lvl ) #else #if defined( __gnuc__ ) #pragma gcc diagnostic push #pragma gcc diagnostic ignored "-wunused-value" #endif   #include <iosfwd> struct nullstream : public std::ostream {     nullstream() : std::ios(0), std::ostream(0) {} };  static nullstream g_nullstream;  #define log_message( lvl ) g_nullstream  #if defined( __gnuc__ ) #pragma gcc diagnostic pop #endif  #endif 

the severity level of log entry meerly acts filter sinks. sink decide message (print or not) based on severity level. message still sent.

if trying not send message @ all, you'll need redefine log_message nothing. there might in boost library this, otherwise, you'll have write own. perhaps 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 though nothing being done log message or expressions make up, the expressions still evaluated. if of these expressions expensive, still take performance hit. example:

log_message (debug) << somesuperexpensivefunction(); 

even if using nulllogger above, somesuperexpensivefunction() still going called.

i suggest alternative adding flag evaluated @ runtime, , decide at runtime whether or not logging:

if (mlogstuff) {    log_message (debug) << somesuperexpensivefunction(); } 

boolean comparisons super cheap, , may find 1 day in future ability turn logging on , off super handy. also, doing means don't need add yet #define, thing.


Comments