Pregunta

I wrote a small logging class that takes two or more arguments:

void my_log(int level, pattern [, fillins...]);

(The pattern and fill-ins are processed in a sprintf-like manner.)

The implementation of my_log begins:

if ( level < _min_level ) return;

I thought this would tidily short-circuit the call to very_elaborate_representation() ...

my_log(DEBUG, "%s", my_object.very_elaborate_representation());

when _min_level is greater than DEBUG.

But it doesn't: apparently (and not surprisingly) arguments are evaluated before the function call.

The formatting is expensive, and intended only for debugging and trouble-shooting.

Is there a clean way to solve this problem with C++11, other than wrapping the call with an if-test?

¿Fue útil?

Solución

Not sure if it helps, but this is how I have previously implemented a logging module:

In the header file:

#define LOG(level,...) do {if (level >= MIN_LEVEL) log_printf(__VA_ARGS__);} while (0)

void log_printf(const char* data,...);

In the source file:

void log_printf(const char* data,...)
{
    char str[64] = {0}; // You can think of other ways for allocating it
    va_list args;
    va_start(args,data);
    vsnprintf(str,sizeof(str),data,args);
    va_end(args);
    printf(str);
}

In order to issue a log message, you only need to call LOG(SOME_LEVEL,some-parameters).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top