Logger.js 999 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. const LEVELS = ['debug', 'info', 'warn', 'error', 'silent'];
  3. const LEVEL_TO_CONSOLE_METHOD = new Map([['debug', 'log'], ['info', 'log'], ['warn', 'log']]);
  4. class Logger {
  5. constructor(level = Logger.defaultLevel) {
  6. this.activeLevels = new Set();
  7. this.setLogLevel(level);
  8. }
  9. setLogLevel(level) {
  10. const levelIndex = LEVELS.indexOf(level);
  11. if (levelIndex === -1) throw new Error(`Invalid log level "${level}". Use one of these: ${LEVELS.join(', ')}`);
  12. this.activeLevels.clear();
  13. for (const [i, level] of LEVELS.entries()) {
  14. if (i >= levelIndex) this.activeLevels.add(level);
  15. }
  16. }
  17. _log(level, ...args) {
  18. console[LEVEL_TO_CONSOLE_METHOD.get(level) || level](...args);
  19. }
  20. }
  21. Logger.levels = LEVELS;
  22. Logger.defaultLevel = 'info';
  23. ;
  24. LEVELS.forEach(level => {
  25. if (level === 'silent') return;
  26. Logger.prototype[level] = function (...args) {
  27. if (this.activeLevels.has(level)) this._log(level, ...args);
  28. };
  29. });
  30. module.exports = Logger;