Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a logging function or macro that can append caller's name to the logging output in C

Tags:

c

logging

macros

I need a logging function or macro in C language, which should works in Linux, that can accept a format string and a list of arguments, and can append the caller's function name to the output string.

Here is an example. Suppose the logging function (macro) is called smart_log. It looks like:

smart_log(const char *fmt, ...)

The first argument fmt is a format string, just like the format string in printf. Following fmt is a list of additional arguments to feed fmt.

Suppose a function called example_function calls smart_log in this way:

void example_function() {
    smart_log("try to output number %d\n", 1);
}

Then the logging string looks like:

[example_function]: try to output number 1

So the key point is that smart_log append the caller's function to the format string.

I am not sure how to achieve this in C. I think it may be possible to use macro to achieve this.

like image 720
RandyTek Avatar asked Oct 21 '25 18:10

RandyTek


1 Answers

There is no portable way for a function to know its caller in C. But you’re right, a macro works:

#define smart_log(...) ( printf("[%s]: ", __func__) , printf(__VA_ARGS__) )

__func__ is defined (C99/C11 6.4.2.2 p.1)

as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function.


Thanks to Hagen von Eitzen for improving my original attempt!

like image 111
mafso Avatar answered Oct 24 '25 09:10

mafso



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!