Created
October 13, 2021 18:36
-
-
Save replete/0a638a63925ca40db2aef9ad3b73fff1 to your computer and use it in GitHub Desktop.
Color-enhanced logger for Typescript Node
This file contains hidden or 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 color = { | |
reset: '\x1b[0m', | |
bright: '\x1b[1m', | |
dim: '\x1b[2m', | |
underscore: '\x1b[4m', | |
blink: '\x1b[5m', | |
reverse: '\x1b[7m', | |
hidden: '\x1b[8m', | |
fgBlack: '\x1b[30m', | |
fgRed: '\x1b[31m', | |
fgGreen: '\x1b[32m', | |
fgYellow: '\x1b[33m', | |
fgBlue: '\x1b[34m', | |
fgMagenta: '\x1b[35m', | |
fgCyan: '\x1b[36m', | |
fgWhite: '\x1b[37m', | |
bgBlack: '\x1b[40m', | |
bgRed: '\x1b[41m', | |
bgGreen: '\x1b[42m', | |
bgYellow: '\x1b[43m', | |
bgBlue: '\x1b[44m', | |
bgMagenta: '\x1b[45m', | |
bgCyan: '\x1b[46m', | |
bgWhite: '\x1b[47m' | |
} | |
interface LogColors { | |
[index: string]: string | |
} | |
const logColors: LogColors = { | |
default: color.dim, | |
error: color.fgRed, | |
info: color.fgBlue, | |
warn: color.fgYellow, | |
success: color.fgGreen | |
} | |
const prefix = (logType: string = '') => | |
`${logColors[logType] || ''}[${new Date() | |
.toISOString() | |
.slice(11) | |
.substring(8, 0)}]` | |
const getArgs = (args: any) => | |
args.length === 1 && typeof args[0] === 'string' ? args[0].toString() : args | |
export default function log(...args: any) { | |
console.log(prefix() + color.reset, getArgs(args)) | |
} | |
log.info = function (...args: any) { | |
console.info(prefix('info'), getArgs(args), color.reset) | |
} | |
log.warn = function (...args: any) { | |
console.warn(prefix('warn'), getArgs(args), color.reset) | |
} | |
log.error = function (...args: any) { | |
console.error(prefix('error'), getArgs(args), color.reset) | |
} | |
log.success = function (...args: any) { | |
console.log(prefix('success'), getArgs(args), color.reset) | |
} | |
log.table = function (...args: any) { | |
console.log(color.dim + prefix() + color.reset) | |
console.table(args) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment