IF_LOG, ELSE_LOG and END_LOG

As you would expect seeing the uppercase spelling, IF_LOG, ELSE_LOG and END_LOG are macros.

The idea behind them is to provide conditional execution of logging code.

 

The macros can be used like follows:

 

 ITLogMsg LogMsg("Main", "DumpDataStructures");
 /* - Depending on the output filter for the default logchannel

the logmessage will be logged or not. */

 IF_LOG(LogMsg) // LogMsg will be logged

  CheckAndDumpDataStructuresToLogMsg(LogMsg);

/* - might be a very time and logging space consuming operation */

 ELSE_LOG // LogMsg won’t be logged

/* Save time doing nothing. */

  ;

 

/* Or: We could produce a cheap mini dump, under a different case

that probably will be logged. */

QuickLog("Main", "MiniDumpDataStructures",
GetMiniDumpOfDataStructuresAsString());

 END_LOG

 

IF_LOG(LogMsg) does not more than to call LogMsg.WillBeLogged() and to branch accordingly using if and opening the "then"-case:

 if(LogMsg.WillBeLogged()) {

  …

The ELSE_LOG case, which can be omitted, expands only to

 }

else {

 …

Finally, END_LOG expands to the closing bracket:

}

 

Note that the filter condition of the logchannels can be modified during run-time, so in the example you can switch the full data structure dump on and off without restarting your program.

 

An advantage of using the macros compared to directly writing the code outlined above is that you can completely deactivate and eliminate the logging code in the IF_LOG cases from you program.
This can be achieved by the following definition:

#define IF_LOG(LogMsg) if(false) {

The actual code elimination only happens when the compiler uses an optimization that recognizes the resulting dead code.