UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

86 lines (85 loc) 2.89 kB
// copy-pasted to avoid weird circular dependency const _noop = (..._args) => undefined; export const commonLogLevelNumber = { debug: 10, log: 20, warn: 20, error: 30, }; /** * SimpleLogger that does nothing (noop). */ export const commonLoggerNoop = { debug: _noop, log: _noop, warn: _noop, error: _noop, }; /** * Creates a "child" logger that is "limited" to the specified CommonLogLevel. */ export function createCommonLoggerAtLevel(logger = console, minLevel = 'log', opt = {}) { const level = commonLogLevelNumber[minLevel]; if (opt.mutate) { if (level > commonLogLevelNumber['debug']) { logger.debug = _noop; if (level > commonLogLevelNumber['log']) { logger.log = _noop; if (level > commonLogLevelNumber['warn']) { logger.warn = _noop; if (level > commonLogLevelNumber['error']) { logger.error = _noop; } } } } return logger; } if (level <= commonLogLevelNumber['debug']) { // All levels are kept return logger; } if (level > commonLogLevelNumber['error']) { // "Log nothing" logger return commonLoggerNoop; } return { debug: _noop, // otherwise it is "log everything" logger (same logger as input) log: level <= commonLogLevelNumber['log'] ? logger.log.bind(logger) : _noop, warn: level <= commonLogLevelNumber['warn'] ? logger.warn.bind(logger) : _noop, error: logger.error.bind(logger), // otherwise it's "log nothing" logger (same as noopLogger) }; } /** * Creates a "proxy" CommonLogger that pipes log messages to all provided sub-loggers. */ export function commonLoggerPipe(loggers) { return { debug: (...args) => loggers.forEach(logger => logger.debug(...args)), log: (...args) => loggers.forEach(logger => logger.log(...args)), warn: (...args) => loggers.forEach(logger => logger.warn(...args)), error: (...args) => loggers.forEach(logger => logger.error(...args)), }; } /** * Creates a "child" CommonLogger with prefix (one or multiple). */ export function commonLoggerPrefix(logger, ...prefixes) { return { debug: (...args) => logger.debug(...prefixes, ...args), log: (...args) => logger.log(...prefixes, ...args), warn: (...args) => logger.warn(...prefixes, ...args), error: (...args) => logger.error(...prefixes, ...args), }; } /** * Creates a CommonLogger from a single function that takes `level` and `args`. */ export function commonLoggerCreate(fn) { return { debug: (...args) => fn('debug', args), log: (...args) => fn('log', args), warn: (...args) => fn('warn', args), error: (...args) => fn('error', args), }; }