LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Variable Argument Programs · Question 4

A levelled logger built on vfprintf in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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
main.c
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links