September 6, 2012

A variable length macro for logging in C++ without format specifiers

I wanted to write a simple logging module for c++. My requirements were simple
  • Nothing fancy but a simple macro to log variables. 
  • No format specifiers like "%s %d" and so on. 
  • Variable argument list
  • Use cout to dump the log messages. Later on this should support logging to syslog if required.
  • Easy to enable and disable with #if 0 and #if 1 declarations.
I did a couple of searches but then most of the implementations were heavy to use and I just wanted a macro that I could enable and disable before compilations.
The following is the simplest I could think of and come up with.
#include <iostream>

#if 1
#define LOG_DEBUG(param) do {     \
  std::cout << param << std::endl;\
} while(0); 
#else
#define LOG_DEBUG(param) do { } while(0);
#endif

int main()
{
  int v1 = 10;
  double v2 = 100223.1212313;
  LOG_DEBUG(1<< " " << 3.5 << " " << "hello" << " " << v1 << " " << v2);
  LOG_DEBUG("Hello");
}
Output is as follows
$> ./a.out 
1 3.5 hello 10 100223
Hello

No comments: