2018-12-19 13:16:45 -05:00
|
|
|
import { LogLevel, getLevelByName, getLevelName } from "./levels.ts";
|
2019-01-02 09:12:48 -05:00
|
|
|
import { BaseHandler } from "./handlers.ts";
|
|
|
|
|
|
|
|
export interface LogRecord {
|
|
|
|
msg: string;
|
|
|
|
args: any[];
|
|
|
|
datetime: Date;
|
|
|
|
level: number;
|
|
|
|
levelName: string;
|
|
|
|
};
|
2018-12-19 13:16:45 -05:00
|
|
|
|
|
|
|
export class Logger {
|
|
|
|
level: number;
|
|
|
|
levelName: string;
|
|
|
|
handlers: any[];
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
constructor(levelName: string, handlers?: BaseHandler[]) {
|
2018-12-19 13:16:45 -05:00
|
|
|
this.level = getLevelByName(levelName);
|
|
|
|
this.levelName = levelName;
|
2019-01-02 09:12:48 -05:00
|
|
|
|
|
|
|
this.handlers = handlers || [];
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
_log(level: number, msg: string, ...args: any[]) {
|
|
|
|
if (this.level > level) return;
|
|
|
|
|
|
|
|
// TODO: it'd be a good idea to make it immutable, so
|
|
|
|
// no handler mangles it by mistake
|
|
|
|
// TODO: iterpolate msg with values
|
|
|
|
const record: LogRecord = {
|
|
|
|
msg: msg,
|
|
|
|
args: args,
|
|
|
|
datetime: new Date(),
|
|
|
|
level: level,
|
|
|
|
levelName: getLevelName(level),
|
|
|
|
}
|
|
|
|
|
2018-12-19 13:16:45 -05:00
|
|
|
this.handlers.forEach(handler => {
|
2019-01-02 09:12:48 -05:00
|
|
|
handler.handle(record);
|
2018-12-19 13:16:45 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
debug(msg: string, ...args: any[]) {
|
|
|
|
return this._log(LogLevel.DEBUG, msg, ...args);
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
info(msg: string, ...args: any[]) {
|
|
|
|
return this._log(LogLevel.INFO, msg, ...args);
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
warning(msg: string, ...args: any[]) {
|
|
|
|
return this._log(LogLevel.WARNING, msg, ...args);
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
error(msg: string, ...args: any[]) {
|
|
|
|
return this._log(LogLevel.ERROR, msg, ...args);
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
|
2019-01-02 09:12:48 -05:00
|
|
|
critical(msg: string, ...args: any[]) {
|
|
|
|
return this._log(LogLevel.CRITICAL, msg, ...args);
|
2018-12-19 13:16:45 -05:00
|
|
|
}
|
|
|
|
}
|