import { object } from "zod"; import { Dispatch } from "./Dispatch"; import { ILogItem } from "./ILogItem"; import { LogLevel } from "./LogLevel"; export class FormattedDispatch extends Dispatch { private formatString: string = "%t %l <%o>: %m"; private levelFixedLength = Object.keys(LogLevel).reduce((acc, cur) => cur.length > acc ? cur.length : acc, 0) private fmtPart(x: any) { switch (typeof x) { case "string": case "number": return x; case "object": return JSON.stringify(x, null, 2); default: return x; } } format(item: ILogItem): string { let data; // Array to string if (Array.isArray(item.data)) data = item.data .map((item: any) => this.fmtPart(item)) .join(" "); else data = this.fmtPart(item.data); return this.formatString .replace("%t", item.timestamp.toISOString()) .replace("%l", LogLevel[item.level].padEnd(this.levelFixedLength)) .replace("%o", item.origin || "") .replace( "%m", data); } process(item: ILogItem): void { if (item.flags?.includes("formatting:none")) return super.process(item); else if (item.flags?.includes("formatting:json_string")) return super.process({...item, data: JSON.stringify(item.data)}); else if (item.flags?.includes("formatting:pretty_json_string")) return super.process({...item, data: JSON.stringify(item.data, null, 2)}); super.process({ ...item, data: this.format(item), }); } }