Skip to content

Instantly share code, notes, and snippets.

@ChaunceyHoover
Last active July 12, 2021 16:10
Show Gist options
  • Save ChaunceyHoover/f4ab2fde7d456316046cb20c9d9051f1 to your computer and use it in GitHub Desktop.
Save ChaunceyHoover/f4ab2fde7d456316046cb20c9d9051f1 to your computer and use it in GitHub Desktop.
My bare minimum logger. Nothing fancy, no extra features, just something to log output with fancy colors.
const { inspect } = require('util');
const chalk = require('chalk');
class Output {
#l = 0;
#c = chalk.grey;
constructor(level, color) {
this.#l = level;
this.#c = color;
}
// Read only - no touchy
get level() { return this.#l; }
get color() { return this.#c; }
}
const level = {
TRACE: new Output(-2, chalk.magenta),
DEBUG: new Output(-1, chalk.green),
INFO: new Output(0, chalk.cyan),
LOG: new Output(NaN, chalk.white),
WARN: new Output(1, chalk.yellow),
ERROR: new Output(2, chalk.red),
CRITICAL: new Output(NaN, chalk.bgRed)
}
// current output level
let logLevel = level.INFO
formatDate = (date) => { return date.toISOString().replace('T', ' ').replace('Z', ''); }
function output(out, ...args) {
if (!isNaN(out.level) && logLevel.level > out.level) return;
let date = new Date();
let proccessed = [];
args[0].forEach(value => {
if (value instanceof Error) proccessed.push(value.stack); // useful info instead of minimal
else if (value instanceof Date) proccessed.push(`[${formatDate(value)}]`); // format dates my preferred way
else if (value instanceof Object) proccessed.push(inspect(value)); // no more [Object object]
else proccessed.push(value);
});
console.log(chalk.grey(`[${formatDate(date)}] `) + out.color(proccessed.join('\t')));
}
const basic_logger = {
// Levels of logging - not mapped dynamically to ignore `LOG` and `CRITICAL`
TRACE: level.TRACE, DEBUG: level.DEBUG, INFO: level.INFO, WARN: level.WARN, ERROR: level.ERROR,
setLevel: (level) => { if (!level instanceof Output) throw new TypeError('Invalid level - please use library defined levels'); logLevel = level },
getLevel: () => { return logLevel; }
}
// Add all the logging functions based off the `Output` object in `level`
Object.keys(level).forEach((key) => basic_logger[key.toLowerCase()] = (...args) => output(level[key], args));
module.exports = basic_logger;
@ChaunceyHoover
Copy link
Author

ChaunceyHoover commented Jul 12, 2021

Example use:

const log = require('minimal-logger');
log.setLevel(log.TRACE);

log.trace('TRACE');
log.debug('DEBUG');
log.info('INFO');
log.log('LOG - Prints no matter what');
log.warn('WARN');
log.error('ERROR');
log.critical('CRITICAL - Also prints no matter what');

Output:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment