// lib/logger.ts import fs from 'fs'; import path from 'path'; export const writeLog = (type: 'REQUEST' | 'RESPONSE' | 'ERROR', title: string, data: any) => { const logProcess = async () => { try { const now = new Date(); const dateStr = now.toISOString().split('T')[0]; const fileName = `${dateStr}.log`; const logDir = path.join(process.cwd(), 'logs'); // Check folder exists (async version is complex, sync check is tiny and runs once) if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir); } const timestamp = now.toISOString(); // Safe stringify to prevent circular reference crashes const dataString = JSON.stringify(data, getCircularReplacer(), 2); const logEntry = `[${timestamp}] [${type}] ${title}\n${dataString}\n${'-'.repeat(50)}\n`; // Async append - we don't wait for this result fs.appendFile(path.join(logDir, fileName), logEntry, (err) => { if (err) console.error('Writing log failed:', err); }); } catch (error) { console.error('Logger internal error:', error); } }; // Trigger execution immediately but don't return a promise to the caller logProcess(); }; // Helper to handle circular references in JSON (common in Axios error objects) const getCircularReplacer = () => { const seen = new WeakSet(); return (key: any, value: any) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return "[Circular]"; } seen.add(value); } return value; }; };