Reputation: 81
I've seen a lot of applications with different log levels, where you can enable/disable them with the level number you specify.
For example, log level 1 has the most details and outputs a lot of detail. Level 2 has less details, level 3 is even less detailed, and level 4 is to disable logging altogether.
Can you please advise on how to implement that in a C application?
Upvotes: 1
Views: 156
Reputation: 881103
It all basically comes down to the logging function. It will be something like:
#define LOG_ALL 0
#define LOG_DEBUG 1
#define LOG_INFO 2
#define LOG_WARN 3
#define LOG_ERROR 4
#define LOG_FATAL 5
#define LOG_NEXTFREE 6
static unsigned int threshold = LOG_WARN;
void logIt (unsigned int level, char *message) {
if (level >= threshold)
puts (message);
}
In other words, the log function will only output a message if the level for that message is sufficient to pass the logging threshold. You call it with things like:
logIt (LOG_INFO, "process starting");
logIt (LOG_FATAL, "cannot read boot sector");
At the default threshold (warning), you will see the latter but not the former.
All you need to add then is a way to modify the threshold dynamically and you can affect what gets logged.
void getAndChangeLevel (unsigned int newLevel) {
if (newLevel < LOG_NEXTFREE)
threshold = newLevel;
}
Of course, there's all sorts of other functionality that may be desirable, I've tried to keep the code simple to illustrate the particular concept you asked about.
Upvotes: 2