import AsyncStorage from '@/utils/kvStore'; interface LogEntry { id: string; timestamp: number; level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'; message: string; data?: any; } class Logger { private static instance: Logger; private readonly maxLogs = 1000; // 最多保存1000条日志 private readonly storageKey = '@app_logs'; static getInstance(): Logger { if (!Logger.instance) { Logger.instance = new Logger(); } return Logger.instance; } private async getLogs(): Promise { try { const logsJson = await AsyncStorage.getItem(this.storageKey); return logsJson ? JSON.parse(logsJson) : []; } catch (error) { console.error('Failed to get logs from storage:', error); return []; } } private async saveLogs(logs: LogEntry[]): Promise { try { // 只保留最新的maxLogs条日志 const trimmedLogs = logs.slice(-this.maxLogs); await AsyncStorage.setItem(this.storageKey, JSON.stringify(trimmedLogs)); } catch (error) { console.error('Failed to save logs to storage:', error); } } private async addLog(level: LogEntry['level'], message: string, data?: any): Promise { const logEntry: LogEntry = { id: Date.now().toString() + Math.random().toString(36).substr(2, 9), timestamp: Date.now(), level, message, data }; // 同时在控制台输出 const logMethod = level === 'ERROR' ? console.error : level === 'WARN' ? console.warn : level === 'INFO' ? console.info : console.log; logMethod(`[${level}] ${message}`, data || ''); try { const logs = await this.getLogs(); logs.push(logEntry); await this.saveLogs(logs); } catch (error) { console.error('Failed to add log:', error); } } async debug(message: string, data?: any): Promise { await this.addLog('DEBUG', message, data); } async info(message: string, data?: any): Promise { await this.addLog('INFO', message, data); } async warn(message: string, data?: any): Promise { await this.addLog('WARN', message, data); } async error(message: string, data?: any): Promise { await this.addLog('ERROR', message, data); } async getAllLogs(): Promise { return await this.getLogs(); } async clearLogs(): Promise { try { await AsyncStorage.removeItem(this.storageKey); } catch (error) { console.error('Failed to clear logs:', error); } } async exportLogs(): Promise { const logs = await this.getLogs(); return JSON.stringify(logs, null, 2); } } // 导出全局日志实例和便捷函数 export const logger = Logger.getInstance(); // 便捷的全局日志函数 export const log = { debug: (message: string, data?: any) => logger.debug(message, data), info: (message: string, data?: any) => logger.info(message, data), warn: (message: string, data?: any) => logger.warn(message, data), error: (message: string, data?: any) => logger.error(message, data), }; export type { LogEntry };