From 6860e525796bf0e83dc1c4f8e3ca6844db7ad4e1 Mon Sep 17 00:00:00 2001 From: zlm Date: Wed, 10 Jun 2026 08:50:43 +0800 Subject: [PATCH] feat: add daily rotating log files (7-day retention) --- .gitignore | 1 + project/src/logger.ts | 59 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/.gitignore b/.gitignore index 8b43ee2..5925486 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ dist/ *.db-wal *.db-shm .env +logs/ diff --git a/project/src/logger.ts b/project/src/logger.ts index d1b8362..88eb6c7 100644 --- a/project/src/logger.ts +++ b/project/src/logger.ts @@ -1,3 +1,11 @@ +import fs from 'fs' +import path from 'path' +import { fileURLToPath } from 'url' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const LOG_DIR = path.resolve(__dirname, '../logs') +const RETENTION_DAYS = 7 + export enum LogLevel { DEBUG = 0, INFO = 1, @@ -14,6 +22,45 @@ const currentLevel = (() => { return LogLevel.INFO })() +if (!fs.existsSync(LOG_DIR)) { + fs.mkdirSync(LOG_DIR, { recursive: true }) +} + +let todayStr = '' +let logStream: fs.WriteStream | null = null + +function rotateLog(): void { + const d = new Date() + const y = d.getFullYear() + const m = String(d.getMonth() + 1).padStart(2, '0') + const dd = String(d.getDate()).padStart(2, '0') + const dateStr = `${y}-${m}-${dd}` + + if (dateStr !== todayStr) { + if (logStream) logStream.end() + todayStr = dateStr + const filePath = path.join(LOG_DIR, `${dateStr}.log`) + logStream = fs.createWriteStream(filePath, { flags: 'a' }) + cleanup() + } +} + +function cleanup(): void { + try { + const files = fs.readdirSync(LOG_DIR) + const now = Date.now() + for (const f of files) { + if (!f.endsWith('.log')) continue + const filePath = path.join(LOG_DIR, f) + const stat = fs.statSync(filePath) + const ageDays = (now - stat.mtimeMs) / 86400000 + if (ageDays > RETENTION_DAYS) { + fs.unlinkSync(filePath) + } + } + } catch { /* ignore */ } +} + function ts(): string { const d = new Date() const y = d.getFullYear() @@ -25,10 +72,20 @@ function ts(): string { return `${y}-${mo}-${dd} ${h}:${mi}:${s}` } +function writeFile(msg: string): void { + try { + rotateLog() + logStream?.write(msg + '\n') + } catch { /* ignore */ } +} + function log(level: LogLevel, tag: string, msg: string, ...args: any[]) { if (level < currentLevel) return const prefix = ['[D]', '[I]', '[W]', '[E]'][level] const full = `${ts()} ${prefix} [${tag}] ${msg}` + + writeFile(full) + if (args.length > 0) { switch (level) { case LogLevel.ERROR: console.error(full, ...args); break @@ -44,6 +101,8 @@ function log(level: LogLevel, tag: string, msg: string, ...args: any[]) { } } +cleanup() + export const logger = { debug: (tag: string, msg: string, ...args: any[]) => log(LogLevel.DEBUG, tag, msg, ...args), info: (tag: string, msg: string, ...args: any[]) => log(LogLevel.INFO, tag, msg, ...args),