UNPKG

@notross/mongo-singleton

Version:

A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.

82 lines 2.77 kB
import util from 'util'; import { LogLevel, } from '../types'; const _console = { debug: console.debug, error: console.error, info: console.info, log: console.log, warn: console.warn, }; /** * Logger with in-memory history, optional console output, * and user-supplied callback support. Supports filtering by level. */ export class Logger { /** * @param props.logging - Whether logs are echoed to console. Defaults to true. * @param props.logLevels - If provided, only these levels will be output. * @param props.callback - Optional function invoked with every log entry. */ constructor(props) { this.callback = null; this.logging = true; this.logs = []; this.debug = this.run.bind(this, LogLevel.debug); this.error = this.run.bind(this, LogLevel.error); this.info = this.run.bind(this, LogLevel.info); this.log = this.run.bind(this, LogLevel.log); this.warn = this.run.bind(this, LogLevel.warn); this.logs = []; if (typeof (props === null || props === void 0 ? void 0 : props.logging) !== 'undefined') { this.logging = props.logging; } if (typeof (props === null || props === void 0 ? void 0 : props.callback) !== 'undefined') { this.callback = props.callback; } if (typeof (props === null || props === void 0 ? void 0 : props.logLevels) !== 'undefined') { this.levels = props.logLevels; } } /** * Set which log levels are allowed to emit. * @param levels - Array of allowed LogLevel values. Undefined resets to all. */ setLevels(levels) { this.levels = levels; } /** * Toggle console logging on or off. * @param logging - If provided, sets explicitly; otherwise flips current state. */ toggleLogging(logging) { if (typeof logging !== 'undefined') { this.logging = logging; } else { this.logging = !this.logging; } } /** * Internal output to console respecting level filters. * @private */ output(level, ...args) { if (!this.logging || (this.levels && !this.levels.includes(level))) { return; } _console[level](...args); } /** * Core log runner; formats the message, stores it, invokes callback, and outputs. * @private */ run(level, ...args) { var _a; const message = util.format(...args); const result = { args, level, message }; this.logs.push(result); (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, result); this.output(level, ...args); } } //# sourceMappingURL=logger.js.map