日志模块拆分 category 参数:log.xxx(category, ...args) 输出 timestamp [level] [category]
- log.js 签名改为 log.xxx(category, ...args);头三段为时间戳 [level] [category],后续参数(含 Error/对象)透传 console 走 util.format
- 所有调用点迁移:从 log.info('[msg] xxx') → log.info('msg', 'xxx');server 启动行无前缀,统一归入 startup
- 实测输出:2026-09-05 09:27:12.068 [debug] [sse] task-20260904-012 event: ping
This commit is contained in:
+12
-6
@@ -1,8 +1,11 @@
|
||||
// 统一日志接口:log.debug/info/warn/error(...),所有输出自带本地时间戳。
|
||||
// 统一日志接口:log.debug/info/warn/error(category, ...args)
|
||||
// 输出格式:<timestamp> [<level>] [<category>] <args...>
|
||||
// category 作为该条日志的标签(原 "[xxx]" 前缀的独立参数化版本),便于日志分类/过滤。
|
||||
// 等级阈值由 config.yml 的 log_level 控制(debug < info < warn < error),
|
||||
// 只有 消息等级 >= 阈值 才输出;配成 none(或 off)则全部静默,含 error。
|
||||
// 启动时 server.js 调 setLevel(cfg.log_level) 注入;改配置需重启生效(与其他配置一致,无热重载)。
|
||||
// 约定:关键动作 info;可预期的异常状况 warn;未预期异常 error;排查细节 debug。
|
||||
// Error 对象等原生参数透传给 console 走 util.format,不会被字符串化。
|
||||
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
|
||||
let threshold = LEVELS.info;
|
||||
|
||||
@@ -21,10 +24,13 @@ function stamp() {
|
||||
|
||||
function emit(fn, level, args) {
|
||||
if (LEVELS[level] < threshold) return;
|
||||
// 时间戳并入首个字符串参数:不影响 %s 占位符,后续参数(含 Error 对象)保持原生格式化
|
||||
if (typeof args[0] === 'string') args[0] = stamp() + ' ' + args[0];
|
||||
else args.unshift(stamp());
|
||||
fn.apply(console, args);
|
||||
// 第一个参数固定为 category(允许为空串但不建议);其余原样透传 console
|
||||
const category = String(args[0] == null ? '' : args[0]);
|
||||
const rest = Array.prototype.slice.call(args, 1);
|
||||
const head = stamp() + ' [' + level + '] [' + category + ']';
|
||||
if (typeof rest[0] === 'string') rest[0] = head + ' ' + rest[0];
|
||||
else rest.unshift(head);
|
||||
fn.apply(console, rest);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
@@ -33,4 +39,4 @@ module.exports = {
|
||||
info() { emit(console.log, 'info', arguments); },
|
||||
warn() { emit(console.warn, 'warn', arguments); },
|
||||
error() { emit(console.error, 'error', arguments); },
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user