Question 4
Back to Exercise
Write a printf-style logger with levels (DEBUG, INFO, ERROR) that drops messages below the current level and forwards the rest to vfprintf.
Solution
#include <stdarg.h>
#include <stdio.h>
enum level { DEBUG, INFO, ERROR };
static const char *names[] = {"DEBUG", "INFO", "ERROR"};
static enum level threshold = INFO;
static int dropped = 0;
static void log_at(enum level lv, const char *fmt, ...) {
if (lv < threshold) {
dropped++;
return;
}
fprintf(stdout, "%-5s | ", names[lv]);
va_list ap;
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
fputc('\n', stdout);
}
int main(void) {
log_at(DEBUG, "cache size %d", 128);
log_at(INFO, "user %s logged in", "ravi");
log_at(ERROR, "payment %d failed: %s", 9041, "timeout");
printf("%d message(s) dropped\n", dropped);
return 0;
}
INFO | user ravi logged in ERROR | payment 9041 failed: timeout 1 message(s) dropped
The logger does not parse the format itself; it hands its va_list to vfprintf. Returning early before va_start is fine.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!