export enum LogLevel { DeepTrace = -3, Trace = -2, Debug = -1, Info = 0, Warn = 1, Error = 2, None = 100000 } /** * Basic logging abstraction supporting * different log levels. */ export class Logger { level: LogLevel; public constructor(level: LogLevel) { this.level = level; } /** * Logs a string internally. It should only be called * once through an internal method to display the * caller that originally logged the string. * * @param prefix - An appended prefix * @param msg - The message including placeholders ({} or {:?}) * @param insertions - The items that replace their respective placeholders * @param msgLevel - The log level of the message */ private log(prefix: string, msg: string, insertions: any[], msgLevel: LogLevel): void { if (this.uses(msgLevel)) { let output = prefix; try { let charIndex = 0; let placeholderIndex = 0; while (charIndex < msg.length) { let c = msg.charAt(charIndex); if (this.substringStartsWith(charIndex, msg, "{}")) { // Insert placeholder let placeholder: any = insertions[placeholderIndex]; let placeholderStr: string; if (placeholder === undefined) { placeholderStr = "undefined"; } else if (placeholder === null) { placeholderStr = "null"; } else if (typeof placeholder === "function") { placeholderStr = placeholder(); } else { placeholderStr = placeholder; } output += placeholderStr; placeholderIndex++; charIndex += 2; } else if (this.substringStartsWith(charIndex, msg, "{:?}")) { // Insert placeholder as JSON output += JSON.stringify(insertions[placeholderIndex]); placeholderIndex++; charIndex += 4; } else { output += c; charIndex++; } } } catch (e) { try { output = prefix + "Exception while logging: " + e; } catch (e2) { output = prefix + "Exception while logging (could not be printed)."; } } console.log(output); } } private substringStartsWith(substrStartIndex: number, str: string, matched: string): boolean { for (let i=0; i