import fs from 'node:fs'; import path from 'node:path'; /** * 사이트 서버 로그 (v1.3.6~). exe 로그(gvr-날짜.log)와 같은 모양의 글 로그를 날짜별 파일로 남긴다. * 게임 PC 와 연결이 끊겨도 사이트에서 볼 수 있다 (관리자만, /site/logs). * * Fastify(pino)가 한 줄씩 쓰는 JSON 을 받아 "시각 수준 [영역] 내용 {추가 값}" 으로 바꾼다. 표준 출력(docker logs)에도 그대로 낸다. */ const LEVELS: Record = { 10: 'TRACE', 20: 'DEBUG', 30: 'INFO ', 40: 'WARN ', 50: 'ERROR', 60: 'FATAL' }; const SKIP_KEYS = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'area', 'reqId', 'err', 'v']); const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; export interface SiteLogOptions { keepDays?: number; /** 표준 출력에도 쓰기 (테스트에서는 끈다) */ echo?: boolean; } export class SiteLog { private day = ''; private fd: number | null = null; private keepDays: number; private echo: boolean; constructor( readonly dir: string, opts: SiteLogOptions = {}, ) { this.keepDays = opts.keepDays ?? 14; this.echo = opts.echo ?? true; fs.mkdirSync(dir, { recursive: true }); } /** pino destination: JSON 한 줄(또는 여러 줄) */ write(chunk: string): void { if (this.echo) process.stdout.write(chunk); for (const line of String(chunk).split('\n')) { if (!line.trim()) continue; let o: Record; try { o = JSON.parse(line); } catch { o = { level: 30, time: Date.now(), msg: line }; } this.append(format(o), typeof o.time === 'number' ? o.time : Date.now()); } } private append(text: string, ts: number): void { const day = new Date(ts).toISOString().slice(0, 10); try { if (day !== this.day || this.fd === null) { if (this.fd !== null) fs.closeSync(this.fd); this.day = day; this.fd = fs.openSync(this.file(day), 'a'); this.cleanup(); } fs.writeSync(this.fd, text + '\n'); } catch { /* 디스크 문제로 로그를 못 써도 서버는 계속 돈다 */ } } file(day: string): string { return path.join(this.dir, `site-${day}.log`); } /** 남아 있는 로그 날짜 (최신 먼저) */ days(): { date: string; size: number }[] { return fs .readdirSync(this.dir) .map((f) => /^site-(\d{4}-\d{2}-\d{2})\.log$/.exec(f)?.[1]) .filter((d): d is string => !!d) .sort() .reverse() .map((date) => ({ date, size: fs.statSync(this.file(date)).size })); } /** 그날 로그 원문. 없으면 null */ read(day: string): string | null { if (!DATE_RE.test(day)) return null; const f = this.file(day); return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null; } private cleanup(): void { const cut = new Date(Date.now() - this.keepDays * 86400000).toISOString().slice(0, 10); for (const { date } of this.days()) if (date < cut) fs.rmSync(this.file(date), { force: true }); } close(): void { if (this.fd !== null) fs.closeSync(this.fd); this.fd = null; } } /** exe 로그와 같은 모양: 2026-10-15T17:15:59.289Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"} */ export function format(o: Record): string { const time = new Date(typeof o.time === 'number' ? o.time : Date.now()).toISOString(); const lv = LEVELS[o.level] ?? 'INFO '; const area = o.area || 'server'; const extra: Record = {}; for (const [k, v] of Object.entries(o)) if (!SKIP_KEYS.has(k) && v !== undefined) extra[k] = v; let s = `${time} ${lv} [${area}] ${o.msg ?? ''}`; if (Object.keys(extra).length) s += ' ' + JSON.stringify(extra); if (o.err) s += `\n ${String(o.err.stack || `${o.err.type ?? 'Error'}: ${o.err.message}`).replace(/\n/g, '\n ')}`; return s; }