jillo-bot/src/lib/log.ts

58 lines
1.3 KiB
TypeScript

import chalk from 'chalk';
import * as util from 'util';
enum Severity {
Info,
Warn,
Error,
Nonsense
}
function severityChar(severity: Severity) {
switch (severity) {
case Severity.Info:
return ' ';
case Severity.Warn:
return chalk.yellow('!');
case Severity.Error:
return chalk.red('!');
case Severity.Nonsense:
return chalk.grey('.');
}
}
const inspectOptions: util.InspectOptions = {
colors: true
};
function format(thing: unknown): string {
if (typeof thing === 'string') {
return thing;
} else if (thing instanceof Error) {
return thing.stack || thing.toString();
} else {
return util.inspect(thing, inspectOptions);
}
}
function log(severity: Severity, ...message: unknown[]) {
const formatted = message
.map(m => format(m))
.reduce((l, r) => l.includes('\n') || r.includes('\n') ? (l + '\n' + r) : (l + ' ' + r), '')
.trim();
const prefix = severityChar(severity) + ' ';
process.stdout.write(`${prefix}${formatted.split('\n').join('\n' + prefix)}\n`);
}
export function info(...message: unknown[]) {
log(Severity.Info, ...message);
}
export function warn(...message: unknown[]) {
log(Severity.Warn, ...message);
}
export function error(...message: unknown[]) {
log(Severity.Error, ...message);
}
export function nonsense(...message: unknown[]) {
log(Severity.Nonsense, ...message);
}