Search code examples
cprintfformatted-input

How do I define a function that accepts a formatted input string in C?


I built a custom logging function that takes in a "log level" and string. A user would specify the log level associated with the message (i.e. error, warning, trace, etc.). The logging function would only print the message to the console depending on the current log level configured.

int global_log_level = INFO;

void logger(int msg_log_level, char * msg)
{
    if(msg_log_level >= global_log_level )
    {
        printf("Log Level = %u: %s", msg_log_level, msg);
    }
}

Ideally, I want to feed formatted strings to this function.

logger(LOG_LEVEL_ERROR, "Error of %u occurred\n", error_code);

However, by adding this "wrapping" logic, I'm unable to input formatted message. Instead, I have to write the message to a temporary string and then feed that into the function.

char temp[512];
sprintf("Error of %u occurred\n", error_code);
logger(LOG_LEVEL_ERROR, temp);

Is there a way to implement the logger function such that I don't need to have the user create a temporary string themselves?


Solution

  • This is question 15.5 on the C FAQ list.

    You want vprintf, which lets you write your own printf-like function logger, but where you can pass the actual format string and arguments off to vprintf to do the work. The trick is that you need to construct a special va_arg type to "point to" the variable-length argument list. It looks like this:

    #include <stdarg.h>
    
    int global_log_level = INFO;
    
    void logger(int msg_log_level, char * msg, ...)
    {
        va_list argp;
        va_start(argp, msg);
    
        if(msg_log_level >= global_log_level )
        {
           printf("Log Level = %u: ", msg_log_level);
           vprintf(msg, argp);
        }
    
        va_end(argp);
    }