Skip to content

Commit a4cc5fa

Browse files
committed
Add automatic cleanup of logs older than 1 year
1 parent 42a8c9c commit a4cc5fa

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

server.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import { migrate } from './config/migrate.js';
3737
import { query, closePool, getPoolStatus } from './config/db.js';
3838
import { getRecentActivity } from './services/activity.js';
3939
import { authenticateToken } from './middleware/auth.js';
40-
import { ensureLogFile, writeLog } from './services/fileLogger.js';
40+
import { ensureLogFile, writeLog, startLogCleaner } from './services/fileLogger.js';
4141

4242
const app = express();
4343

@@ -360,6 +360,7 @@ async function startServer() {
360360
const server = app.listen(PORT, () => {
361361
console.log(`ZeroHost Dashboard running on port ${PORT}`);
362362
startScheduler();
363+
startLogCleaner();
363364
});
364365

365366
function shutdown(signal) {

services/fileLogger.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { appendFile, access, constants } from 'fs/promises';
1+
import { appendFile, access, constants, readFile, writeFile } from 'fs/promises';
22
import { resolve, dirname } from 'path';
33
import { fileURLToPath } from 'url';
44

@@ -135,6 +135,34 @@ export async function ensureLogFile() {
135135
}
136136
}
137137

138+
const ONE_YEAR = 365 * 24 * 60 * 60 * 1000;
139+
140+
export async function cleanOldLogs() {
141+
try {
142+
const content = await readFile(LOG_FILE, 'utf-8');
143+
if (!content) return;
144+
const cutoff = Date.now() - ONE_YEAR;
145+
const lines = content.split('\n').filter(line => {
146+
if (!line.trim()) return false;
147+
const match = line.match(/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]/);
148+
if (!match) return true;
149+
const ts = new Date(match[1].replace(' ', 'T') + 'Z').getTime();
150+
return ts >= cutoff;
151+
});
152+
const cleaned = lines.join('\n') + (lines.length > 0 ? '\n' : '');
153+
await writeFile(LOG_FILE, cleaned, 'utf-8');
154+
} catch (err) {
155+
if (err.code !== 'ENOENT') {
156+
console.error('Failed to clean old logs:', err.message);
157+
}
158+
}
159+
}
160+
161+
export function startLogCleaner() {
162+
cleanOldLogs();
163+
setInterval(cleanOldLogs, 24 * 60 * 60 * 1000);
164+
}
165+
138166
export async function writeLog(method, path, ip) {
139167
const label = getActionLabel(method, path);
140168
const date = new Date();

0 commit comments

Comments
 (0)