Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print logs on both console and file in C language?

Tags:

c

printf

I have come across many questions related to this but my requirement is quite different. I developed a C application(mib-test.c) earlier which uses fprintf at lot of places. fprintf logs the messages in a file.

But now I need to print these messages to console also. I am looking for a solution in which I do not need to change fprintf in all the places.

Is there a way to do it?

like image 990
Raxesh Oriya Avatar asked Oct 26 '25 11:10

Raxesh Oriya


2 Answers

No, there is not, you will have to edit each instance. A better approach to begin with would have been to create your own logging function or macro. I would suggest you to do that now, and save yourself some time if you ever change mind again in the future.

Example using a function:

void log(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);

    va_start(args, fmt);
    vfprintf(logfile, fmt, args);
    va_end(args);
}

Example using a macro:

#define log(fmt, ...) do {                                    \
                          fprintf(stderr, fmt, __VA_ARGS__);  \
                          fprintf(logfile, fmt, __VA_ARGS__); \
                      } while (0)

See also: do { ... } while (0) — what is it good for?

Note that using a macro will evaluate expressions twice. For example log("%d\n", get_int()); using the macro form will call get_int() twice. You should only use the macro if you plan to pass simple values.

Both solutions assume that logfile is global and already opened for writing. You could actually define it static inside the function and handle the initial opening checking if (logfile == NULL) before doing anything.

like image 164
Marco Bonelli Avatar answered Oct 29 '25 01:10

Marco Bonelli


@marcobonelli wrote a great answer. So for the replacing part, if you're not using an IDE that can do all the replacements for you, you could probably use this simple sed command to do all the replacement. Assume you have a log function like in this answer, then just do this:

sed 's/fprintf(logfile/log(/g' -i <file>
like image 28
klutt Avatar answered Oct 29 '25 03:10

klutt



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!