Add configurable log levels

This commit is contained in:
powermaker450 2024-08-21 11:49:54 -04:00
parent 0aea8e7464
commit a94d683293
2 changed files with 22 additions and 10 deletions

View file

@ -2,6 +2,7 @@ declare global {
namespace NodeJS { namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
PORT: string; PORT: string;
LOG_LEVEL: string;
} }
} }
} }

View file

@ -4,32 +4,43 @@ export class Logger {
private _wrn: string; private _wrn: string;
private _err: string; private _err: string;
private _main: string; private _main: string;
private _logLevel = +process.env.LOG_LEVEL || 1;
public name: string;
public isMainFunction: boolean;
constructor(origin?: string) { constructor(origin?: string) {
this._wrn = chalk.yellow("[WARN] "); this._wrn = chalk.yellow("[WARN] ");
this._err = chalk.red("[ERROR] "); this._err = chalk.red("[ERROR] ");
this.name = origin ?? "Anonymous";
this.isMainFunction = this.name === "Main";
this._main = chalk.bold.gray(`[SRS | ${emp(origin ?? "Anonymous")}] `); this._main = chalk.bold.gray(`[SRS | ${emp(this.name)}] `);
} }
public log(text?: any, args?: any): void { public log(text?: any, args?: any): void {
if (this.isMainFunction || this._logLevel === 0) {
args args
? console.log(this._main + text, args) ? console.log(this._main + text, args)
: console.log(this._main + text); : console.log(this._main + text);
} }
}
public warn(text?: any, args?: any): void { public warn(text?: any, args?: any): void {
if (this._logLevel === 1) {
args args
? console.warn(this._main + this._wrn + text, args) ? console.warn(this._main + this._wrn + text, args)
: console.warn(this._main + this._wrn + text); : console.warn(this._main + this._wrn + text);
} }
}
public error(text?: any, args?: any): void { public error(text?: any, args?: any): void {
if (this._logLevel === 2) {
args args
? console.error(this._main + this._err + text, args) ? console.error(this._main + this._err + text, args)
: console.error(this._main + this._err + text); : console.error(this._main + this._err + text);
} }
} }
}
export const emp = chalk.green; export const emp = chalk.green;
export const wrn = chalk.yellow; export const wrn = chalk.yellow;