LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Scope and Hoisting Coding Problems · Question 4

Configurable logger with levels in JavaScript Solution, output & explanation

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

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");

Output Verified by running it on Node.js

[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.

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