roohan
roohan

Reputation: 751

Writing a macro for logging

I'm writing a logging class at the moment. The Logger works with streams and also prints the object which is logging at the moment. Here is the macro:

#define OBJLOG(DL, what) DL <= this->Logger->getDebugLevel() ? *this->Logger << DL << "[" << this->Name << "]: "<< what << std::endl : this->Logger->doNothing();

The pseudo code Variant for better overview:

#define OBJLOG(debuglevel, what) debuglevel <= logger.debuglevel ? logger.log(what) : logger.doNothing()

Is there any way to get around the doNothing function call, like doing nothing at all?

Upvotes: 3

Views: 636

Answers (3)

Derek Ledbetter
Derek Ledbetter

Reputation: 4885

If you want an expression that does nothing, try (void)0.

Upvotes: 0

Electro
Electro

Reputation: 3074

#define OBJLOG(DL, what) do { if(DL <= this->Logger->getDebugLevel()) *this->Logger << DL << "[" << this->Name << "]: "<< what << std::endl; } while(0)

See Why use apparently meaningless do-while and if-else statements in macros? for an explanation. (The do {} while(0) isn't strictly necessary here, but I would prefer not to leak an ostream.)

Also, you should always wrap macro argument uses in parentheses, like:

#define OBJLOG(DL, what) do { if((DL) <= this->Logger->getDebugLevel()) *this->Logger << (DL) << "[" << this->Name << "]: "<< (what) << std::endl; } while(0)

Finally, you should move this code into a function and call that in your macro (if you really insist on using a macro) to avoid evaluating your macro arguments more than once.

Upvotes: 4

Anon Mail
Anon Mail

Reputation: 4770

  1. Have your logger.log() function return a boolean.

  2. Connect your predicates with an and like this: debuglevel <= logger.debuglevel && logger.log

That should do the trick.

Upvotes: 1

Related Questions