'use strict'; const fs = require('fs'); const path = require('path'); const LOG_FILE_PATH = path.join(__dirname, '../logs.txt'); const MAX_LOG_BYTES = 1024 * 1024; function formatLogLine (level, message, details = null) { const timestamp = new Date().toISOString(); const parts = [`[${timestamp}]`, `[${level}]`, String(message || '')]; if (details) { if (details.stack) { parts.push(String(details.stack)); } else if (details.message) { parts.push(String(details.message)); } else { try { parts.push(JSON.stringify(details)); } catch { parts.push(String(details)); } } } return parts.join(' ') + '\n'; } function trimToLimit (contents) { let text = String(contents || ''); if (Buffer.byteLength(text, 'utf8') <= MAX_LOG_BYTES) return text; const lines = text.split(/\r?\n/); while (lines.length > 1 && Buffer.byteLength(lines.join('\n'), 'utf8') > MAX_LOG_BYTES) { lines.shift(); } text = lines.join('\n'); if (text && !text.endsWith('\n')) text += '\n'; return text; } function appendLogLine (line) { try { fs.mkdirSync(path.dirname(LOG_FILE_PATH), { recursive: true }); const existing = fs.existsSync(LOG_FILE_PATH) ? fs.readFileSync(LOG_FILE_PATH, 'utf8') : ''; fs.writeFileSync(LOG_FILE_PATH, trimToLimit(existing + line), 'utf8'); } catch { // Logging must never interfere with the request path. } } function logError (message, error = null, details = null) { if (process.env.NODE_ENV === 'test') return; const payload = details || {}; if (error && !payload.stack) { payload.stack = error.stack || error.message || String(error); } appendLogLine(formatLogLine('ERROR', message, payload)); } module.exports = { LOG_FILE_PATH, logError, };