Skip to content
Middle+5 views

Extend the logging system so that a single call to saveAdmin for the admin service can perform several required logging actions—for example, output info and log messages simultaneously—and support different transports, including console and alert, without compromising the solution's extensibility.

Practice

AI answer

Separate the choice of actions from their execution: saveAdmin passes the event to loggers, and each logger is responsible for one action and transport. This lets you combine, for example, info in the console and log via an alert independently, without adding conditions to saveAdmin.

const transports = {
  console: {
    info: message => console.info(message),
    log: message => console.log(message),
  },
  alert: {
    info: message => window.alert(message),
    log: message => window.alert(message),
  },
};

function createLogger({ transport, level }) {
  return message => transports[transport][level](message);
}

const adminLoggers = [
  createLogger({ transport: 'console', level: 'info' }),
  createLogger({ transport: 'alert', level: 'log' }),
];

function saveAdmin(admin) {
  // Save admin...
  const message = `Admin saved: ${admin.name}`;
  adminLoggers.forEach(logger => logger(message));
}

In a real application, logger configuration should be passed through dependency injection, and unknown transports and levels should be validated when creating a logger. To add an action or transport, simply register a new implementation without changing saveAdmin.