import path from "path"; import { DEBUG } from "./variables"; import fs from "fs"; export class Logger { public currentLogFile: string; public tag?: string; private get pathToLogFile(): string { return path.join(__dirname, "../log", this.currentLogFile); } constructor(options?: { tag?: string }) { this.currentLogFile = this.createNewLogFile(); if (options !== undefined) { this.tag = options.tag; } } private createNewLogFile() { const date = new Date().toISOString().split("T"); date[1] = date[1].split(".")[0].replaceAll(":", "-"); const fileName = `${date}.log`; fs.writeFileSync(this.pathToLogFile, ""); return fileName; } private toString(object: any) { if (typeof object === "object") return Object.prototype.toString.call(object); else if (Array.isArray(object)) return object.join(); else if (typeof object === "number") return object.toString(); else if (typeof object === "boolean") return object.toString(); else if (typeof object === "string") return object; return "Cannot transfrom object to string"; } private writeEntryToFile( options: { tag?: string; type: "log" | "error" | "warn" | "info"; divider?: string; }, ...args: any ) { const strings: string[] = []; for (const argument of args) { const string = this.toString(argument); strings.push(string); } const dateString = new Date().toLocaleString(undefined, { formatMatcher: "best fit", dateStyle: "short", timeStyle: "medium", }); const divider = options.divider === undefined ? "\n\t" : options.divider; let string = `[${dateString}] `; if (this.tag !== undefined) string += `[LTAG: ${this.tag}`; if (options.tag !== undefined) string += ` TAG: ${options.tag}] `; else string += "] "; string += `[${options.type.toUpperCase()}] `; string += strings.join(divider); fs.appendFileSync(this.pathToLogFile, string); } public log(...args: any) { if (!DEBUG) console.log(...args); this.writeEntryToFile({ type: "log" }, ...args); } public error(...args: any) { if (!DEBUG) console.error(...args); this.writeEntryToFile({ type: "error" }, ...args); } public warn(...args: any) { if (!DEBUG) console.warn(...args); this.writeEntryToFile({ type: "warn" }, ...args); } public info(...args: any) { if (!DEBUG) console.info(...args); this.writeEntryToFile({ type: "info" }, ...args); } }