import {Env} from '../env';
import {MessageContext} from '../log';
import {Constructor} from '../providers';
import {joinFqn} from '../util';
export const BASE_ROOT = 'ts-base';
let internalLog: InternalLog;
type InternalLogOptions = {
parent?: string | { fqn: string };
enable: { warn: boolean; debug: boolean; table: boolean };
console?: Console;
}
const defaultOptions: InternalLogOptions = { enable: { table: false, warn: false, debug: false } };
export class InternalLog {
readonly fqn: string;
protected readonly console: Console;
constructor(readonly name: string, readonly options: InternalLogOptions = defaultOptions) {
this.fqn = joinFqn(name, options.parent);
this.console = options.console || console;
}
warn(message: string, ...args: unknown[]): void {
this.options.enable.warn && this.console.warn(`${this.fqn}: ${message}`, ...args);
}
debug(message: string, ...args: unknown[]): void {
this.options.enable.debug && this.console.debug(`${this.fqn}: ${message}`, ...args);
}
table(tabularData: any, properties?: string[]): void {
this.options.enable.table && this.console.table(tabularData, properties);
}
extend(name): InternalLog {
return new InternalLog(name, {
...this.options,
parent: this,
});
}
}
export function logger(name: string | { name: string } | Constructor<any>, _console?: Console): InternalLog {
let log: InternalLog = internalLog;
if (!log) {
const options = { ...defaultOptions, console: _console };
const env = Env.root();
const enable = env?.getProp(BASE_ROOT) || 'false';
switch (enable) {
case 'true':
options.enable = { table: true, warn: true, debug: true };
break;
case 'warn':
options.enable = { table: false, warn: true, debug: true };
break;
case 'debug':
options.enable = { table: false, warn: false, debug: true };
break;
case 'table':
options.enable = { table: true, warn: false, debug: false };
break;
}
log = new InternalLog(BASE_ROOT, options);
if (env) {
internalLog = log;
}
}
return log.extend(name);
}
export function debug(name: string): (message: string | MessageContext, ...args: unknown[]) => void {
const log = logger(name);
const debugFn = log.debug;
return debugFn.bind(log);
}
export const MSG_FMT = {
annotatingClass: 'Annotating Class %s with @%s(%o)',
annotatingMethod: 'Annotating Method %s.%s with @%s(%o)',
};
|