90 lines
2.1 KiB
TypeScript
90 lines
2.1 KiB
TypeScript
/**
|
||
* Logger 日志工具类
|
||
*
|
||
* 功能:
|
||
* - 按等级输出日志(debug/info/warn/error)
|
||
* - 在 Dev/Test 环境下输出全部日志
|
||
* - 在 Prod 环境下只输出 error
|
||
* - 可扩展日志上报(比如接入远程日志系统)
|
||
*/
|
||
|
||
import { AppConfig } from "db://assets/Scripts/chat18x/config/env/appConfig";
|
||
|
||
export enum LogLevel {
|
||
Debug = 0,
|
||
Info = 1,
|
||
Warn = 2,
|
||
Error = 3,
|
||
None = 4, // 不打印任何日志
|
||
}
|
||
|
||
class Logger {
|
||
private level: LogLevel;
|
||
|
||
constructor() {
|
||
// 根据环境决定日志等级
|
||
if (AppConfig.I.isDev()) {
|
||
this.level = LogLevel.Debug; // Dev 输出所有日志
|
||
} else if (AppConfig.I.isTest()) {
|
||
this.level = LogLevel.Debug; // Test 输出所有日志
|
||
} else if (AppConfig.I.isProd()) {
|
||
this.level = LogLevel.Error; // Prod 只输出 error
|
||
} else {
|
||
this.level = LogLevel.None; // 不打印任何日志
|
||
}
|
||
console.log("日志等级:", this.level);
|
||
}
|
||
|
||
/** 修改日志等级(运行时可动态调整) */
|
||
public setLevel(level: LogLevel) {
|
||
this.level = level;
|
||
}
|
||
|
||
public debug(...args: any[]) {
|
||
if (this.level <= LogLevel.Debug) {
|
||
console.debug("[DEBUG]", ...args);
|
||
}
|
||
}
|
||
|
||
public info(...args: any[]) {
|
||
if (this.level <= LogLevel.Info) {
|
||
console.info("[INFO]", ...args);
|
||
}
|
||
}
|
||
|
||
public log(...args: any[]) {
|
||
if (this.level <= LogLevel.Info) {
|
||
console.log("[LOG]", ...args);
|
||
}
|
||
}
|
||
|
||
public warn(...args: any[]) {
|
||
if (this.level <= LogLevel.Warn) {
|
||
console.warn("[WARN]", ...args);
|
||
}
|
||
}
|
||
|
||
public error(...args: any[]) {
|
||
if (this.level <= LogLevel.Error) {
|
||
console.error("[ERROR]", ...args);
|
||
// 这里也可以加远程上报,例如:
|
||
// this.reportError(args);
|
||
}
|
||
}
|
||
|
||
// 示例:远程上报错误日志
|
||
private reportError(args: any[]) {
|
||
try {
|
||
// fetch("https://log-server.xxx.com/report", {
|
||
// method: "POST",
|
||
// body: JSON.stringify({ msg: args, time: Date.now() }),
|
||
// });
|
||
} catch (e) {
|
||
console.error("日志上报失败", e);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 全局单例
|
||
export const logger = new Logger();
|