I have a multi file C program. I\'d like the user to be able to specify different debugging levels at run time.
What is the best way to implement this?
I was thi
Jonathan's suggestion is good but since C99 we have variadic macros so one doesn't need to use double braces for debug macro.
There is a light version of logging header I use:
#define LOG_FATAL (1)
#define LOG_ERR (2)
#define LOG_WARN (3)
#define LOG_INFO (4)
#define LOG_DBG (5)
#define LOG(level, ...) do { \
if (level <= debug_level) { \
fprintf(dbgstream,"%s:%d:", __FILE__, __LINE__); \
fprintf(dbgstream, __VA_ARGS__); \
fprintf(dbgstream, "\n"); \
fflush(dbgstream); \
} \
} while (0)
extern FILE *dbgstream;
extern int debug_level;
So wherever I need to log something, I just add line like
LOG(LOG_ERR, "I/O error %s occured while opening file %s", strerror(errno), filename);
During program initialisation you need to specify values for dbgstream
(usually defaults to stderr
) and debug_level
.
For real projects instead of calling fprintf
many times I just call my function from LOG
macro and pass __FILE__
, __LINE__
and __VA_ARGS_
as argument - that function also prints date, time and pid in log line, and don't do fflush()
every time - only when buffering counter exceeds preset value - itsignificantly increases logging performance.
But please be aware that some compilers may not support variadic macros as it was introduced only in C99.