// 日志:同时写终端和日志文件(文件超上限就轮转成 .1)。 // // 用法: // import { openLog, closeLog, log, warn, error } from './log.mjs'; // openLog(file, maxBytes); // 不调用就只打终端 // log('信息A', { x: 1 }); // → [2026-01-01 00:00:00] [信息] 信息A {"x":1} // // 终端面板(tui.mjs)启用时会把「终端」这一路改道到面板的日志区(setConsoleSink), // 文件那一路始终是纯文本逐行 —— 面板不会污染日志文件,grep / 采集不受影响。 // // 注意:openLog 必须在任何写文件之前调用;closeLog 在进程退出路径上兜底调用。 import fs from 'node:fs'; import path from 'node:path'; let stream = null; /** 终端输出目标;null = 直接 console.log(未启用面板时的默认行为) */ let consoleSink = null; /** * 接管 / 归还终端输出。传 null 恢复逐行 console.log。 * sink(level, text) 收到的是完整的一行(不含换行)。 * @param {null | ((level: string, text: string) => void)} fn */ export function setConsoleSink(fn) { consoleSink = typeof fn === 'function' ? fn : null; } /** 打开日志文件;maxBytes 为单文件上限,超出时把现有文件改名成 .1 */ export function openLog(file, maxBytes) { try { fs.mkdirSync(path.dirname(file), { recursive: true }); try { const st = fs.statSync(file); if (st.size > maxBytes) fs.renameSync(file, file + '.1'); } catch (e) { /* 文件还不存在 */ } stream = fs.createWriteStream(file, { flags: 'a' }); } catch (e) { console.error('[日志] 无法写入 ' + file + ':' + e.message); } } /** 关闭日志文件(可重复调用) */ export function closeLog() { if (!stream) return; try { stream.end(); } catch (e) { /* ignore */ } finally { stream = null; } } export function isLogOpen() { return stream !== null; } const clock = () => new Date().toISOString().replace('T', ' ').slice(0, 19); function line(level, args) { const text = '[' + clock() + '] [' + level + '] ' + args.map(function (a) { if (typeof a === 'string') return a; try { return JSON.stringify(a); } catch (e) { return String(a); } }).join(' '); if (consoleSink) { try { consoleSink(level, text); } catch (e) { /* 面板异常不影响日志文件 */ } } else { console.log(text); } if (stream) { try { stream.write(text + '\n'); } catch (e) { /* ignore */ } } } export const log = (...a) => line('信息', a); export const warn = (...a) => line('警告', a); export const error = (...a) => line('错误', a);