index.uts 2.66 KB
import { writeLog as nativeWriteLog, getLogFiles as nativeGetLogFiles, removeLogFile as nativeRemoveLogFile } from "./utssdk/index.uts";
import { LogLevel, LogFile } from "./utssdk/interface.uts";

export type RemoteLogHandler = (level: LogLevel, tag: string, msg: string) => void;

export class Logger {
    private tag: string = "AppLogger";
    private remoteHandler: RemoteLogHandler | null = null;

    constructor() {
        // 默认清理7天前的日志
        // 注意:这里最好延迟执行,避免应用启动时卡顿
        /*
        setTimeout(() => {
            this.cleanOldLogs(7);
        }, 5000);
        */
    }

    setTag(tag: string) {
        this.tag = tag;
    }

    /**
     * 设置远程日志处理器
     * 用于接入 Sentry 或其他日志服务
     */
    setRemoteHandler(handler: RemoteLogHandler) {
        this.remoteHandler = handler;
    }

    debug(msg: any) {
        this.write("debug", msg);
    }

    info(msg: any) {
        this.write("info", msg);
    }

    warn(msg: any) {
        this.write("warn", msg);
    }

    error(msg: any) {
        this.write("error", msg);
    }

    private write(level: LogLevel, msg: any) {
        const msgStr = this.formatMsg(msg);
        
        // 1. 控制台输出
        const consoleMsg = `[${this.tag}] ${msgStr}`;
        switch (level) {
            case "debug": console.debug(consoleMsg); break;
            case "info": console.log(consoleMsg); break;
            case "warn": console.warn(consoleMsg); break;
            case "error": console.error(consoleMsg); break;
        }

        // 2. 本地文件写入 (Native)
        nativeWriteLog(level, this.tag, msgStr);

        // 3. 远程日志 (如果有)
        if (this.remoteHandler != null) {
            this.remoteHandler!(level, this.tag, msgStr);
        }
    }

    private formatMsg(msg: any | null): string {
        if (msg == null) return "null";
        if (typeof msg === 'string') {
            return msg;
        }
        if (msg instanceof Error) {
            return msg.message;
        }
        try {
            return JSON.stringify(msg);
        } catch (e) {
            return "" + msg;
        }
    }

    // --- 管理接口 ---

    /**
     * 获取日志文件列表
     */
    getLogFiles(): LogFile[] {
        return nativeGetLogFiles();
    }

    /**
     * 删除指定日志文件
     */
    removeLogFile(path: string) {
        nativeRemoveLogFile(path);
    }
    
    /**
     * 清理旧日志
     * @param days 保留天数
     */
    /*
    cleanOldLogs(days: number) {
        // nativeCleanOldLogs(days);
    }
    */
}

export const logger = new Logger();
export { LogLevel, LogFile };