LearnFrenzy
Sign in Take a free test

Abstraction · Abstraction Programs · Question 7

Logger interface with console and filter loggers in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Define a Logger interface and implement ConsoleLogger, MemoryLogger and a FilterLogger that wraps any other logger and passes on only messages at or above a minimum level.

Solution
main.cpp
#include <iostream>
#include <string>
#include <vector>

enum class Level { debug, info, error };

struct Logger {
    virtual void log(Level lv, const std::string& msg) = 0;
    virtual ~Logger() = default;
};

struct ConsoleLogger : Logger {
    void log(Level lv, const std::string& msg) override {
        static const char* names[] = {"DEBUG", "INFO", "ERROR"};
        std::cout << '[' << names[static_cast<int>(lv)] << "] " << msg << '\n';
    }
};

struct MemoryLogger : Logger {
    std::vector<std::string> lines;
    void log(Level, const std::string& msg) override { lines.push_back(msg); }
};

class FilterLogger : public Logger {            // a logger built from another logger
    Logger& inner_;
    Level min_;
public:
    FilterLogger(Logger& inner, Level min) : inner_(inner), min_(min) {}
    void log(Level lv, const std::string& msg) override { if (lv >= min_) inner_.log(lv, msg); }
};

void checkout(Logger& log) {
    log.log(Level::debug, "cart loaded");
    log.log(Level::info, "payment started");
    log.log(Level::error, "card declined");
}

int main() {
    ConsoleLogger console;
    FilterLogger important(console, Level::info);
    checkout(important);
    MemoryLogger mem;
    checkout(mem);
    std::cout << mem.lines.size() << " lines in memory\n";
    return 0;
}

Output Verified by compiling and running

[INFO] payment started
[ERROR] card declined
3 lines in memory

checkout() depends only on Logger. FilterLogger is a decorator: it is itself a Logger and adds behaviour around another one.

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