1
0
silverbullet/plugos/environments/custom_logger.ts

65 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-05-09 12:59:12 +00:00
export type LogLevel = "info" | "warn" | "error" | "log";
export class ConsoleLogger {
print: boolean;
callback: (level: LogLevel, entry: string) => void;
constructor(
callback: (level: LogLevel, entry: string) => void,
2022-10-12 09:47:13 +00:00
print: boolean = true,
2022-05-09 12:59:12 +00:00
) {
this.print = print;
this.callback = callback;
}
log(...args: any[]): void {
this.push("log", args);
}
warn(...args: any[]): void {
this.push("warn", args);
}
error(...args: any[]): void {
this.push("error", args);
}
info(...args: any[]): void {
this.push("info", args);
}
push(level: LogLevel, args: any[]) {
this.callback(level, this.logMessage(args));
if (this.print) {
console[level](...args);
}
}
logMessage(values: any[]): string {
2022-10-15 17:02:56 +00:00
const pieces: string[] = [];
for (const val of values) {
2022-05-09 12:59:12 +00:00
switch (typeof val) {
case "string":
case "number":
pieces.push("" + val);
break;
2022-05-13 12:36:26 +00:00
case "undefined":
pieces.push("undefined");
break;
2022-05-09 12:59:12 +00:00
default:
try {
let s = JSON.stringify(val, null, 2);
if (s.length > 500) {
s = s.substring(0, 500) + "...";
}
pieces.push(s);
} catch {
// May be cyclical reference
pieces.push("[circular object]");
}
}
}
return pieces.join(" ");
}
}