Write createLogger(name, minLevel) returning debug, info, warn and error functions that print only messages at or above minLevel, prefixed with the logger name.
Solution
main.js
const LEVELS = ["debug", "info", "warn", "error"];
function createLogger(name, minLevel = "info") {
const min = LEVELS.indexOf(minLevel);
const logger = {};
for (const level of LEVELS) {
logger[level] = (msg) => {
if (LEVELS.indexOf(level) >= min) console.log(`[${name}] ${level.toUpperCase()}: ${msg}`);
};
}
return logger;
}
const db = createLogger("db", "warn");
const api = createLogger("api", "debug");
db.info("connected"); // below warn: hidden
db.error("query timeout");
api.debug("GET /users");
api.warn("slow response");
Each logger function closes over name, min and its own level (const in for…of gives every iteration a new binding). The two loggers have separate settings.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!