// 日志:INFO 屏蔽大体积 JSON 调试日志;DEBUG 模式开启完整输出(AGENTS.md 规范)。 "use strict"; const fs = require("fs"); const path = require("path"); const LEVELS = { DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40 }; const DEBUG = process.env.DEBUG === "1" || process.env.DEBUG === "true"; const DEFAULT_MAX_BYTES = 10 * 1024 * 1024; // 单文件 10MB const DEFAULT_KEEP = 3; // 保留 3 份轮转文件(.1/.2/.3) let _file = null; // 日志文件路径(按行 append) let _maxBytes = DEFAULT_MAX_BYTES; let _keep = DEFAULT_KEEP; function setLogFile(filePath) { _file = filePath; try { fs.mkdirSync(path.dirname(filePath), { recursive: true }); } catch (e) { _file = null; } } // 设置中心可调:单文件上限(MB)与保留份数;传 null/非法值回退内置默认 function setRotation(opts) { const o = opts || {}; const mb = Number(o.maxMb); const keep = Number(o.keep); _maxBytes = Number.isFinite(mb) && mb >= 1 ? Math.round(mb * 1024 * 1024) : DEFAULT_MAX_BYTES; _keep = Number.isFinite(keep) && keep >= 1 ? Math.round(keep) : DEFAULT_KEEP; } function rotation() { return { maxMb: Math.round((_maxBytes / 1024 / 1024) * 10) / 10, keep: _keep }; } function logDir() { return _file ? path.dirname(_file) : ""; } // 当前日志文件清单(base + .1..keep),供设置页展示占用 function logFiles() { if (!_file) return []; const out = []; const names = [_file]; for (let i = 1; i <= _keep; i++) names.push(`${_file}.${i}`); for (const f of names) { try { const st = fs.statSync(f); out.push({ name: path.basename(f), size: st.size, mtime: st.mtime.toISOString() }); } catch (e) { /* 未生成的文件跳过 */ } } return out; } // 按大小轮转:shell.log → shell.log.1 → ... → shell.log.(丢弃最旧) function rotateIfNeeded() { if (!_file) return; try { const st = fs.statSync(_file); if (st.size < _maxBytes) return; for (let i = _keep - 1; i >= 1; i--) { const a = `${_file}.${i}`; const b = `${_file}.${i + 1}`; if (fs.existsSync(a)) fs.renameSync(a, b); } if (fs.existsSync(_file)) fs.renameSync(_file, `${_file}.1`); } catch (e) { /* 轮转失败忽略 */ } } function ts() { const d = new Date(); const p = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; } function write(level, name, msg) { if (LEVELS[level] < LEVELS[DEBUG ? "DEBUG" : "INFO"]) return; const line = `${ts()} ${level.padEnd(7)} ${name} ${msg}`; console.log(line); if (_file) { try { rotateIfNeeded(); fs.appendFileSync(_file, line + "\n", "utf-8"); } catch (e) { /* 落盘失败静默 */ } } } function makeLogger(name) { return { debug: (msg) => write("DEBUG", name, msg), info: (msg) => write("INFO", name, msg), warning: (msg) => write("WARNING", name, msg), error: (msg) => write("ERROR", name, msg), }; } module.exports = { makeLogger, setLogFile, setRotation, rotation, logDir, logFiles, isDebug: DEBUG, };