Files
game_voice_recorder/site/server/src/site-log.ts
EJClaw fa6126e17f v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창
- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:01:14 +09:00

110 lines
3.8 KiB
TypeScript

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<number, string> = { 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<string, any>;
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, any>): 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<string, unknown> = {};
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;
}