UNPKG

perfect-logger

Version:

A zero-dependency, isomorphic logger for Node.js and Browsers with plugin support.

95 lines (94 loc) 3.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LogManager = void 0; const constants_1 = require("../constants"); const Logger_1 = require("./Logger"); const ConsoleAppender_1 = require("../appenders/ConsoleAppender"); const FileAppender_1 = require("../appenders/FileAppender"); /** * The singleton LogManager class. * It holds the central configuration and dispatches log entries to the appenders. */ class LogManager { constructor() { this.config = { minLevel: constants_1.LogLevel.INFO, appenders: [], timezone: undefined, }; } static getInstance() { if (!LogManager.instance) { LogManager.instance = new LogManager(); } return LogManager.instance; } /** * A convenience method to quickly configure the logger for a typical Node.js backend. * Includes a ConsoleAppender and a FileAppender with sensible defaults. * @param config Overrides for the default backend configuration. */ static simpleBackendConfig(config = {}) { const defaultConfig = { minLevel: constants_1.LogLevel.INFO, appenders: [ new ConsoleAppender_1.ConsoleAppender(), new FileAppender_1.FileAppender({ minLevel: constants_1.LogLevel.DEBUG, logDirectory: 'logs', }), ], }; LogManager.getInstance().configure({ ...defaultConfig, ...config }); } /** * A convenience method to quickly configure the logger for a typical frontend. * Includes a ConsoleAppender with sensible defaults. * @param config Overrides for the default backend configuration. */ static simpleFrontendConfig(config = {}) { const defaultConfig = { minLevel: constants_1.LogLevel.INFO, appenders: [ new ConsoleAppender_1.ConsoleAppender() ], }; LogManager.getInstance().configure({ ...defaultConfig, ...config }); } /** * Configures the LogManager. This should be called once at application startup. * @param config The configuration object. */ configure(config) { this.config = { ...this.config, ...config }; // Pass the global timezone to appenders that don't have one this.config.appenders.forEach(appender => { if ('timezone' in appender && !appender.timezone) { appender.timezone = this.config.timezone; } }); } /** * Creates a new Logger instance. * @param namespace The name of the logger. * @returns A new Logger. */ getLogger(namespace) { return new Logger_1.Logger(this, namespace); } /** * Dispatches a log entry to all configured appenders. * This is called by the Logger instances. * @param entry The log entry to dispatch. */ dispatch(entry) { if (entry.level >= this.config.minLevel) { for (const appender of this.config.appenders) { // The type assertion is a bit of a hack, but it's necessary // because the Appender interface doesn't have a log method. appender.log(entry); } } } } exports.LogManager = LogManager;