Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Izzo Avatar asked Nov 01 '25 21:11

Izzo


1 Answers

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);
}
like image 104
Steve Summit Avatar answered Nov 03 '25 12:11

Steve Summit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!