// Import necessary modules import debug from 'debug'; import { config } from 'dotenv'; config(); import { promises as fs } from 'fs'; import { join, dirname } from 'path'; import { inspect } from 'util'; /** * Write a given message to the log file * @param {any} logMessage The message to write to the log file * @param {string} appName The app name that created the log entry */ const writeToLog = async (logMessage, appName) => { const logLocation = join(process.env.LOG_LOCATION ?? `./logs/${appName}.log`); // Ensure the log directory exists try { await fs.mkdir(dirname(logLocation), { recursive: true }); } catch (err) { console.error(err); } // Ensure the message is a string logMessage = `${String(logMessage)}\n`; // Write to the file try { await fs.writeFile(logLocation, logMessage, { encoding: 'utf-8', flag: 'a+' }); } catch (err) { console.error(err); } }; /** * Create the different logging methods for a function * Namespace template = ("[app]:[fileName]:['INFO', 'WARNING', 'DEBUG', 'ERROR']") * @param {string} appName The name of the app to be used in the 'app' portion of the namespace * @param {string} fileName The name of the file calling the builder to be used in the 'fileName' portion of the namespace */ export class DebugBuilder { constructor(appName, fileName) { const buildLogger = (level) => (...messageParts) => { const logger = debug(`${appName}:${fileName}:${level}`); logger(messageParts); const timeStamp = new Date().toLocaleString('en-US', { timeZone: 'America/New_York' }); const message = `${timeStamp} - ${appName}:${fileName}:${level}\t-\t${messageParts.map(part => inspect(part)).join(' ')}`; // Write to console console.log(message); // Write to logfile writeToLog(message, appName); }; this.INFO = buildLogger('INFO'); this.DEBUG = buildLogger('DEBUG'); this.VERBOSE = buildLogger('VERBOSE'); this.WARN = buildLogger('WARNING'); this.ERROR = (...messageParts) => { buildLogger('ERROR')(...messageParts); if (process.env.EXIT_ON_ERROR && process.env.EXIT_ON_ERROR > 0) { writeToLog("!--- EXITING ---!", appName); const exitDelay = parseInt(process.env.EXIT_ON_ERROR_DELAY, 10) || 0; setTimeout(() => process.exit(1), exitDelay); } }; } }