One of the reasons you report debug information to stderr
rather than stdout
because stdout
might be sent down a pipeline and your diagnostics would go with the actual data, confusing the subsequent phases of the pipeline.
If you might want to redirect the output, or add timestamps (or PID, or any other information), then do not use fprintf()
directly. Call a function of your own devising which deals with the information you want in the way you want.
Thus, your macro could be:
extern void dbg_print(const char *fmt, ...);
#define DEBUG_PRINT(fmt, ...) \
do { if (DEBUG_TEST) dbg_print(fmt, __VA_ARGS__); } while (0)
Or:
extern void dbg_print(const char *func, const char *file, int line, const char *fmt, ...);
#define DEBUG_PRINT(fmt, ...) \
do { if (DEBUG_TEST) dbg_print(__func__, __FILE__, __LINE__, fmt, __VA_ARGS__); } while (0)
This includes the function name, file name and line number in the information
For example, I have a moderately complex package that does that. One of the core internal routines is:
/* err_stdio - report error via stdio */
static void err_stdio(FILE *fp, int flags, int errnum, const char *format, va_list args)
{
if ((flags & ERR_NOARG0) == 0)
fprintf(fp, "%s: ", arg0);
if (flags & ERR_STAMP)
{
char timbuf[32];
fprintf(fp, "%s - ", err_time(timbuf, sizeof(timbuf)));
}
if (flags & ERR_PID)
fprintf(fp, "pid=%d: ", (int)getpid());
vfprintf(fp, format, args);
if (flags & ERR_ERRNO)
fprintf(fp, "error (%d) %s\n", errnum, strerror(errnum));
}
The debug wrappers can call onto that function with appropriate flags, and generate the desired output. Other parts of the system control the file stream used (stderr
is the default, but there's a function to redirect the output to any other stream), and so on.
If you limit yourself by using fprintf()
directly in the debug macro, you are stuck with what fprintf()
can do, or recompiling everything.
See also my answer to 'C #define macro for debug printing' for more information about debugging macros and how to use them (though it looks as if you've taken much of what I say there on board already).