fix: add periodic log rotation to prevent unbounded log growth (#160)
Log rotation previously only ran at startup, causing logs to grow indefinitely on long-running processes (reported up to 71GB/day). Now checks file size every 60 seconds and truncates when exceeding 3MB. Fixes #155 Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4,25 +4,33 @@ import { mkdirSync, statSync, truncateSync, openSync, readSync, closeSync, write
|
|||||||
import { homedir } from 'os'
|
import { homedir } from 'os'
|
||||||
|
|
||||||
const MAX_LOG_SIZE = 3 * 1024 * 1024 // 3MB
|
const MAX_LOG_SIZE = 3 * 1024 * 1024 // 3MB
|
||||||
|
const CHECK_INTERVAL = 60_000 // Check every minute
|
||||||
|
|
||||||
const logDir = resolve(homedir(), '.hermes-web-ui', 'logs')
|
const logDir = resolve(homedir(), '.hermes-web-ui', 'logs')
|
||||||
mkdirSync(logDir, { recursive: true })
|
mkdirSync(logDir, { recursive: true })
|
||||||
|
|
||||||
const logFile = resolve(logDir, 'server.log')
|
const logFile = resolve(logDir, 'server.log')
|
||||||
|
|
||||||
// Rotate log if it exceeds MAX_LOG_SIZE — truncate to keep the last half
|
function rotateIfNeeded() {
|
||||||
try {
|
try {
|
||||||
const stat = statSync(logFile)
|
const stat = statSync(logFile)
|
||||||
if (stat.size > MAX_LOG_SIZE) {
|
if (stat.size > MAX_LOG_SIZE) {
|
||||||
const keepSize = Math.floor(MAX_LOG_SIZE / 2)
|
const keepSize = Math.floor(MAX_LOG_SIZE / 2)
|
||||||
const fd = openSync(logFile, 'r')
|
const fd = openSync(logFile, 'r')
|
||||||
const buf = Buffer.alloc(keepSize)
|
const buf = Buffer.alloc(keepSize)
|
||||||
readSync(fd, buf, 0, keepSize, stat.size - keepSize)
|
readSync(fd, buf, 0, keepSize, stat.size - keepSize)
|
||||||
closeSync(fd)
|
closeSync(fd)
|
||||||
truncateSync(logFile, 0)
|
truncateSync(logFile, 0)
|
||||||
writeFileSync(logFile, buf)
|
writeFileSync(logFile, buf)
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate on startup
|
||||||
|
rotateIfNeeded()
|
||||||
|
|
||||||
|
// Periodic rotation check — prevents unbounded log growth
|
||||||
|
setInterval(rotateIfNeeded, CHECK_INTERVAL)
|
||||||
|
|
||||||
export const logger = pino({
|
export const logger = pino({
|
||||||
level: process.env.LOG_LEVEL || 'info',
|
level: process.env.LOG_LEVEL || 'info',
|
||||||
|
|||||||
Reference in New Issue
Block a user