core/src/core/logger.ts

120 lines
2.5 KiB
TypeScript

import dateFmt from 'dateformat';
import util from 'util';
type LogType = 'info' | 'debug' | 'warn' | 'error';
/**
* Logger for all of Squeebot. Use this instead of console.log/warn/error!
*/
export class Logger {
private console = [console.log, console.warn, console.error];
constructor(
public timestamp = 'dd/mm/yy HH:MM:ss'
) {}
/**
* Set node.js readline consideration
* @param rl Readline instance
*/
public setReadline(rl: any): void {
for (const index in this.console) {
const old = this.console[index];
this.console[index] = (...data: any[]): void => {
rl.output.write('\x1b[2K\r');
old(...data);
rl.prompt(true);
};
}
}
/**
* Write out to log
* @param ltype Logger level
* @param data Data to log
*/
private write(ltype: LogType, ...data: any[]): void {
const message = [];
let cfunc = this.console[0];
if (this.timestamp) {
message.push(`[${dateFmt(new Date(), this.timestamp)}]`);
}
switch (ltype) {
case 'info':
message.push('[ INFO]');
break;
case 'debug':
message.push('[DEBUG]');
break;
case 'warn':
message.push('[ WARN]');
cfunc = this.console[1];
break;
case 'error':
message.push('[ERROR]');
cfunc = this.console[2];
break;
}
// Short dance to apply formatting
let final = data[0];
if (data.length > 1) {
const fargs = data.slice(1);
final = util.format(data[0], ...fargs);
}
message.push(final);
cfunc(...message);
}
/**
* Logger level: `INFO`
*
* See `console.log` for more information.
*/
public log(...data: any[]): void {
this.write('info', ...data);
}
/**
* Logger level: `WARN`
*
* See `console.warn` for more information.
*/
public warn(...data: any[]): void {
this.write('warn', ...data);
}
/**
* Logger level: `INFO`
*
* See `console.log` for more information.
*/
public info(...data: any[]): void {
this.write('info', ...data);
}
/**
* Logger level: `ERROR`
*
* See `console.error` for more information.
*/
public error(...data: any[]): void {
this.write('error', ...data);
}
/**
* Logger level: `DEBUG`
*
* See `console.log` for more information.
*/
public debug(...data: any[]): void {
this.write('debug', ...data);
}
}
// Create singleton for Logger to be used anywhere
const logger = new Logger();
export { logger };