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.
Asked at
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.
Also asked at ООО «Софтнетикс» (Softnetix)
- Tell us about yourself, your experience, and your recent projects.
- What is memoization in React and how do useMemo, useCallback, and React.memo work?
- Tell me about XSS attacks: types and protection methods.
- What static methods of Promise do you know? Tell about them.
- Why is using array index as a key an anti-pattern in React?
Similar questions
- What is web solution scaling?
- We urgently need to connect a prototype to several services with different APIs and transports (REST, WebSocket), collect and analyze metrics. What will be the plan of action?
- What is the difference between providing a service at the module level and at the component level?
- How to extend the solution: fetch users in parallel and return username instead of userId for each post?
- What will console.log output? (context task: user object with greet method, calling the method directly and through a variable)