index.uts 4.54 KB
import File from "java.io.File";
import FileWriter from "java.io.FileWriter";
import BufferedWriter from "java.io.BufferedWriter";
import SimpleDateFormat from "java.text.SimpleDateFormat";
import Date from "java.util.Date";
import Locale from "java.util.Locale";
import { LogFile } from "../interface.uts";

class LogManager {
    private static instance: LogManager | null = null;
    private logDir: File | null = null;
    private dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private timeFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());

    private constructor() {
        const context = UTSAndroid.getAppContext();
        if (context != null) {
            const externalDir = context.getExternalFilesDir(null);
            if (externalDir != null) {
                this.logDir = new File(externalDir, "uni_log");
                if (!this.logDir!.exists()) {
                    this.logDir!.mkdirs();
                }
            }
        }
    }

    static getInstance(): LogManager {
        if (LogManager.instance == null) {
            LogManager.instance = new LogManager();
        }
        return LogManager.instance!;
    }

    write(level: string, tag: string, msg: string) {
        if (this.logDir == null) return;

        const now = new Date();
        const dateStr = this.dateFormat.format(now);
        const timeStr = this.timeFormat.format(now);
        const fileName = `${dateStr}.txt`;
        const logFile = new File(this.logDir, fileName);

        const content = `${timeStr} [${level}] [${tag}] ${msg}\n`;

        try {
            // true for append mode
            const writer = new FileWriter(logFile, true);
            const bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(content);
            bufferedWriter.close();
        } catch (e) {
            console.error("LogManager write error: " + e.message);
        }
    }

    getLogFiles(): LogFile[] {
        const files: LogFile[] = [];
        if (this.logDir != null && this.logDir!.exists()) {
            const fileList = this.logDir!.listFiles();
            if (fileList != null) {
                // UTS Android 中,Java 数组的长度属性可能映射为 size 或者 length
                // 但如果是原生 Array,应该用 .size 或 .length?
                // 尝试直接使用 for...of 遍历,或者将其转换为 List
                // 实际上 listFiles() 返回 File[],在 Kotlin/UTS 中可能被视为 Array<File>
                // 报错提示 'length' 找不到,可能是因为需要显式声明类型或转换
                
                // 强制转换为 UTSArray 或 List 可能比较麻烦,尝试最简单的 for-each
                for (let i: Int = 0; i < fileList.size; i++) {
                     const file = fileList[i];
                     if (file.isFile() && file.getName().endsWith(".txt")) {
                        const logFile = {
                            name: file.getName(),
                            path: file.getAbsolutePath(),
                            size: file.length().toDouble(), // interface defined as number (Double)
                            lastModified: file.lastModified().toDouble() // interface defined as number
                        } as LogFile;
                        files.push(logFile);
                    }
                }
            }
        }
        // sort by lastModified desc
        return files.sort((a, b) => b.lastModified - a.lastModified);
    }

    removeLogFile(path: string) {
        const file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
    
    cleanOldLogs(days: number) {
        const now = new Date().getTime();
        const msPerDay = (24 * 60 * 60 * 1000).toLong();
        const threshold = now - (days.toLong() * msPerDay);
        
        const files = this.getLogFiles();
        files.forEach(file => {
             // lastModified 返回的是 Long
             if (file.lastModified < threshold) {
                 this.removeLogFile(file.path);
             }
        });
    }
}

export const writeLog = (level: string, tag: string, msg: string) => {
    LogManager.getInstance().write(level, tag, msg);
}

export const getLogFiles = (): LogFile[] => {
    return LogManager.getInstance().getLogFiles();
}

export const removeLogFile = (path: string) => {
    LogManager.getInstance().removeLogFile(path);
}

/*
export const cleanOldLogs = (days: number) => {
    // LogManager.getInstance().cleanOldLogs(days);
}
*/