Last active
July 12, 2021 16:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use:
Output: