2022-11-03 16:34:58 +08:00

81 lines
2.4 KiB
TypeScript

export default class Log {
private static logs = '';
private static counter = { info: 0, error: 0, warning: 0 };
public static info(...o): void {
Log.counter.info++;
let time = this.getTime();
let flag = '[WH] IFO';
if (this.debug()) {
console.log(flag, time, ...o);
}
this.saveLogs(flag, time, ...o);
}
public static error(...o): void {
Log.counter.error++;
let time = this.getTime();
let flag = '[WH] ERR';
console.error(flag, time, ...o);
this.saveLogs(flag, time, ...o);
}
public static warn(...o): void {
Log.counter.warning++;
let time = this.getTime();
let flag = '[WH] WRN';
(this.debug()) && (console.warn(flag, time, ...o));
this.saveLogs(flag, time, ...o);
}
public static debug(): boolean {
let ret: boolean = true;
try {
let local = JSON.parse(localStorage.getItem('wh_trans_settings'));
if (local) ret = local['isDev'];
} catch {
}
return ret;
}
public static getTime(): string {
let d = new Date();
let year = d.getFullYear();
let month = ('0' + (d.getMonth() + 1)).slice(-2);
let date = ('0' + d.getDate()).slice(-2);
let hours = ('0' + d.getHours()).slice(-2);
let minutes = ('0' + d.getMinutes()).slice(-2);
let seconds = ('0' + d.getSeconds()).slice(-2);
let ms = ('00' + d.getMilliseconds()).slice(-3);
return `[${ year }-${ month }-${ date } ${ hours }:${ minutes }:${ seconds }.${ ms }]`;
}
public static getLogs() {
return this.logs;
}
private static saveLogs(...o) {
o.forEach(item => {
if (typeof item === 'string') this.logs += item;
else if (item !== null && item !== undefined) {
let json = '{}';
let name = item.toString ? item.toString() : 'UNKNOWN_OBJECT';
try {
json = JSON.stringify(item);
name = Object.getPrototypeOf(item).constructor.name;
} catch {
}
this.logs += ` [${ name }] [${ json }] `;
}
})
this.logs += '\r\n';
}
public static getCounter() {
return {
info: Log.counter.info,
error: Log.counter.error,
warning: Log.counter.warning,
}
}
}