UNPKG

jet-logger

Version:

A super quick, easy to setup logging tool for NodeJS/TypeScript.

220 lines (219 loc) 6.72 kB
import colors from 'colors'; import fs from 'fs'; import util from 'util'; const LOGGER_MODES = { Console: 'CONSOLE', File: 'FILE', Custom: 'CUSTOM', Off: 'OFF', }; const FORMATS = { Line: 'LINE', Json: 'JSON', }; const LEVELS = { Info: { Color: 'green', Prefix: 'INFO', }, Important: { Color: 'magenta', Prefix: 'IMPORTANT', }, Warning: { Color: 'yellow', Prefix: 'WARNING', }, Error: { Color: 'red', Prefix: 'ERROR', }, }; const DEFAULTS = { mode: LOGGER_MODES.Console, filePath: 'jet-logger.log', timestamp: true, format: FORMATS.Line, customLogFn: () => ({}), }; const Errors = { CustomLogger: 'Custom logger mode set to true, but no custom logger was provided.', Mode: 'The correct logger mode was not specified: Must be "CUSTOM", "FILE", ' + '"OFF", or "CONSOLE".', }; export const JetLogger = { Modes: LOGGER_MODES, Formats: FORMATS, }; export function jetLogger(options) { let mode = DEFAULTS.mode, filePath = DEFAULTS.filePath, timestamp = DEFAULTS.timestamp, format = DEFAULTS.format, customLogFn = DEFAULTS.customLogFn; if (options?.mode !== undefined) { mode = options.mode; } else if (!!process.env.JET_LOGGER_MODE) { mode = process.env.JET_LOGGER_MODE.toUpperCase(); } if (mode === LOGGER_MODES.Off) { return { info: (_, __) => ({}), imp: (_, __) => ({}), warn: (_, __) => ({}), err: (_, __) => ({}), }; } if (mode === LOGGER_MODES.Custom) { if (options?.customLogger !== undefined) { customLogFn = options.customLogger; } if (!customLogFn) { throw Error(Errors.CustomLogger); } return { info: setupPrintWithCustomLogger(LEVELS.Info, customLogFn), imp: setupPrintWithCustomLogger(LEVELS.Important, customLogFn), warn: setupPrintWithCustomLogger(LEVELS.Warning, customLogFn), err: setupPrintWithCustomLogger(LEVELS.Error, customLogFn), }; } if (options?.filepath !== undefined) { filePath = options.filepath; } else if (!!process.env.JET_LOGGER_FILEPATH) { filePath = process.env.JET_LOGGER_FILEPATH; } if (options?.timestamp !== undefined) { timestamp = options.timestamp; } else if (!!process.env.JET_LOGGER_TIMESTAMP) { const envVar = process.env.JET_LOGGER_TIMESTAMP; timestamp = envVar.toUpperCase() === 'TRUE'; } if (options?.format !== undefined) { format = options.format; } else if (!!process.env.JET_LOGGER_FORMAT) { format = process.env.JET_LOGGER_FORMAT.toUpperCase(); } let formatter = () => ''; if (format === FORMATS.Line) { formatter = setupLineFormatter(timestamp); } else if (format === FORMATS.Json) { formatter = setupJsonFormatter(timestamp); } if (mode === LOGGER_MODES.File) { let filePathDatetime = true; if (options?.filepathDatetimeParam !== undefined) { filePathDatetime = options.filepathDatetimeParam; } else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) { const envVar = process.env.JET_LOGGER_FILEPATH_DATETIME; filePathDatetime = envVar.toUpperCase() === 'TRUE'; } if (filePathDatetime) { filePath = addDatetimeToFileName(filePath); } return { info: setupPrintToFile(LEVELS.Info, formatter, filePath), imp: setupPrintToFile(LEVELS.Important, formatter, filePath), warn: setupPrintToFile(LEVELS.Warning, formatter, filePath), err: setupPrintToFile(LEVELS.Error, formatter, filePath), }; } return { info: setupPrintToConsole(LEVELS.Info, formatter), imp: setupPrintToConsole(LEVELS.Important, formatter), warn: setupPrintToConsole(LEVELS.Warning, formatter), err: setupPrintToConsole(LEVELS.Error, formatter), }; } function setupPrintWithCustomLogger(level, customLogFn) { return (content, printFull) => { let contentNew; if (printFull) { contentNew = util.inspect(content); } else { contentNew = String(content); } return customLogFn(new Date(), level.Prefix, contentNew); }; } function setupLineFormatter(timestamp) { if (timestamp) { return (content, level) => { const contentNew = level.Prefix + ': ' + content, time = '[' + new Date().toISOString() + '] '; return time + contentNew; }; } else { return (content, level) => { return level.Prefix + ': ' + content; }; } } function setupJsonFormatter(timestamp) { if (timestamp) { return (content, level) => { const json = { level: level.Prefix, message: content, }; json.timestamp = new Date().toISOString(); return JSON.stringify(json); }; } else { return (content, level) => { const json = { level: level.Prefix, message: content, }; return JSON.stringify(json); }; } } function setupPrintToFile(level, formatter, filePath) { return (content, printFull) => { let contentNew; if (!!printFull) { contentNew = util.inspect(content); } else { contentNew = String(content); } contentNew = formatter(contentNew, level); fs.appendFile(filePath, contentNew, (err) => { if (!!err) { console.error(err); } }); }; } function setupPrintToConsole(level, formatter) { return (content, printFull) => { let contentNew; if (!!printFull) { contentNew = util.inspect(content); } else { contentNew = String(content); } const colorFn = colors[level.Color]; contentNew = formatter(contentNew, level); console.log(colorFn(contentNew)); }; } function addDatetimeToFileName(filePath) { const dateStr = new Date() .toISOString() .split('-') .join('') .split(':') .join('') .slice(0, 15); const filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = dateStr + '_' + fileName; filePathArr[lastIdx] = fileNameNew; return filePathArr.join('/'); } export default jetLogger();