| 1 | 'use strict'; |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const path = require('path'); |
| 5 | |
| 6 | const LOG_FILE_PATH = path.join(__dirname, '../logs.txt'); |
| 7 | const MAX_LOG_BYTES = 1024 * 1024; |
| 8 | |
| 9 | function formatLogLine (level, message, details = null) |
| 10 | { |
| 11 | const timestamp = new Date().toISOString(); |
| 12 | const parts = [`[${timestamp}]`, `[${level}]`, String(message || '')]; |
| 13 | |
| 14 | if (details) |
| 15 | { |
| 16 | if (details.stack) |
| 17 | { |
| 18 | parts.push(String(details.stack)); |
| 19 | } else if (details.message) |
| 20 | { |
| 21 | parts.push(String(details.message)); |
| 22 | } else |
| 23 | { |
| 24 | try |
| 25 | { |
| 26 | parts.push(JSON.stringify(details)); |
| 27 | } catch |
| 28 | { |
| 29 | parts.push(String(details)); |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return parts.join(' ') + '\n'; |
| 35 | } |
| 36 | |
| 37 | function trimToLimit (contents) |
| 38 | { |
| 39 | let text = String(contents || ''); |
| 40 | if (Buffer.byteLength(text, 'utf8') <= MAX_LOG_BYTES) return text; |
| 41 | |
| 42 | const lines = text.split(/\r?\n/); |
| 43 | while (lines.length > 1 && Buffer.byteLength(lines.join('\n'), 'utf8') > MAX_LOG_BYTES) |
| 44 | { |
| 45 | lines.shift(); |
| 46 | } |
| 47 | |
| 48 | text = lines.join('\n'); |
| 49 | if (text && !text.endsWith('\n')) text += '\n'; |
| 50 | return text; |
| 51 | } |
| 52 | |
| 53 | function appendLogLine (line) |
| 54 | { |
| 55 | try |
| 56 | { |
| 57 | fs.mkdirSync(path.dirname(LOG_FILE_PATH), { recursive: true }); |
| 58 | const existing = fs.existsSync(LOG_FILE_PATH) ? fs.readFileSync(LOG_FILE_PATH, 'utf8') : ''; |
| 59 | fs.writeFileSync(LOG_FILE_PATH, trimToLimit(existing + line), 'utf8'); |
| 60 | } catch |
| 61 | { |
| 62 | // Logging must never interfere with the request path. |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | function logError (message, error = null, details = null) |
| 67 | { |
| 68 | if (process.env.NODE_ENV === 'test') return; |
| 69 | |
| 70 | const payload = details || {}; |
| 71 | if (error && !payload.stack) |
| 72 | { |
| 73 | payload.stack = error.stack || error.message || String(error); |
| 74 | } |
| 75 | |
| 76 | appendLogLine(formatLogLine('ERROR', message, payload)); |
| 77 | } |
| 78 | |
| 79 | module.exports = { |
| 80 | LOG_FILE_PATH, |
| 81 | logError, |
| 82 | }; |