Avoiding many #ifdefs for logging statements

In our application, we have created our own registration system . There are several different types of logs in this logging system , debugging, error, warning, communication, performance and .... There are many #ifdef and #endif to disable a particular type of log . These #ifdef and #endif make the code hard to read.

We are thinking of removing these #ifdef and #endif and having a check before writing the message to a file. This means that there are many “ useless ” calls to the logging system . These calls will not result in any record.

Is there a better way to enable / disable the log type without these #ifdef and #endif these “ useless ” calls? AND

+4
source share
2 answers

How about the following:

// comment out if not needed
#define ENABLE_LOG

#ifdef ENABLE_LOG
#  define LOG(x) x
#else
#  define LOG(x) (void) 0 
#endif

Later you could just call:

LOG(mylogger.call());

Updated part #elseproposed by Dietrich Epp.

+7
source

#define, ,

template<bool B>
void log(std::string message){}

template<>
void log<true>(std::string message){log_internal(message);}

#define DEBUG true
#define COMMUNICATION false

...

log<DEBUG>("this message will be logged");
log<COMMUNICATION>("this message won't");

#define , :

  • - .. log . namespace, #define .

  • , . LOG(x) , x - , .

-

LOG(std::cout << "Here!" << endl);

. 2 - endl undefined . , , , ( , ) , ( ! :()

Edit

:

, , ( ). , . , inline .

, std::string const char *, , - .

, , , #define. - #define , , .

+7

All Articles