1import {logger, fileAsyncTransport} from 'react-native-logs'; 2import RNFS, {readDir, readFile} from 'react-native-fs'; 3import pathConst from '@/constants/pathConst'; 4import Config from '../core/config'; 5import {addLog} from '@/lib/react-native-vdebug/src/log'; 6 7const config = { 8 transport: fileAsyncTransport, 9 transportOptions: { 10 FS: RNFS, 11 filePath: pathConst.logPath, 12 fileName: `error-log-{date-today}.log`, 13 }, 14 dateFormat: 'local', 15}; 16 17const traceConfig = { 18 transport: fileAsyncTransport, 19 transportOptions: { 20 FS: RNFS, 21 filePath: pathConst.logPath, 22 fileName: `trace-log.log`, 23 }, 24 dateFormat: 'local', 25}; 26 27const log = logger.createLogger(config); 28const traceLogger = logger.createLogger(traceConfig); 29 30export function trace( 31 desc: string, 32 message?: any, 33 level: 'info' | 'error' = 'info', 34) { 35 if (__DEV__) { 36 console.log(desc, message); 37 } 38 // 特殊情况记录操作路径 39 if (Config.get('setting.basic.debug.traceLog')) { 40 traceLogger[level]({ 41 desc, 42 message, 43 }); 44 } 45} 46 47export async function clearLog() { 48 const files = await RNFS.readDir(pathConst.logPath); 49 await Promise.all( 50 files.map(async file => { 51 if (file.isFile()) { 52 try { 53 await RNFS.unlink(file.path); 54 } catch {} 55 } 56 }), 57 ); 58} 59 60export async function getErrorLogContent() { 61 try { 62 const files = await readDir(pathConst.logPath); 63 console.log(files); 64 const today = new Date(); 65 // 两天的错误日志 66 const yesterday = new Date(); 67 yesterday.setDate(today.getDate() - 1); 68 const todayLog = files.find( 69 _ => 70 _.isFile() && 71 _.path.endsWith( 72 `error-log-${today.getDate()}-${ 73 today.getMonth() + 1 74 }-${today.getFullYear()}.log`, 75 ), 76 ); 77 const yesterdayLog = files.find( 78 _ => 79 _.isFile() && 80 _.path.endsWith( 81 `error-log-${yesterday.getDate()}-${ 82 yesterday.getMonth() + 1 83 }-${yesterday.getFullYear()}.log`, 84 ), 85 ); 86 let logContent = ''; 87 if (todayLog) { 88 logContent += await readFile(todayLog.path, 'utf8'); 89 } 90 if (yesterdayLog) { 91 logContent += await readFile(yesterdayLog.path, 'utf8'); 92 } 93 return logContent; 94 } catch { 95 return ''; 96 } 97} 98 99export function errorLog(desc: string, message: any) { 100 if (Config.get('setting.basic.debug.errorLog')) { 101 log.error({ 102 desc, 103 message, 104 }); 105 trace(desc, message, 'error'); 106 } 107} 108 109export function devLog( 110 method: 'log' | 'error' | 'warn' | 'info', 111 ...args: any[] 112) { 113 if (Config.get('setting.basic.debug.devLog')) { 114 addLog(method, args); 115 } 116} 117 118export {log}; 119