From 63fcf8d096c395646977b0e3f52500c67ea64f4b Mon Sep 17 00:00:00 2001 From: yanhuojiyusheng <2398249916@qq.com> Date: Sat, 24 Oct 2026 19:45:38 +0800 Subject: [PATCH] fix(logger): stamp log lines with the system's local time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bili.log 每行都用 `new Date().toISOString()` 打戳:永远是 UTC 并以 Z 结尾, 而系统时钟(`date` / timedatectl)给的是本地时间。排查时两者差着整个时区 偏移(本机 CST 是 8 小时),日志里刚发生的事件看起来像是几小时前,必须 手工换算才能和终端、浏览器、宿主日志对齐。 - `logTimestamp()` 输出本地墙上时间 `YYYY-MM-DDTHH:mm:ss.SSS`(无后缀), 与 `date` 逐字对齐;两处打戳点(file+stderr 与降级 warn)统一走它; - 读侧兼容:该格式没有时区标记,历史日志里全是 `Z` 结尾,`logs-query` 的 时间窗过滤与 `acp-cache-diff` 的 usage 行解析都放宽为"时区段可选", 同一文件里新旧两种戳都能解析(裸戳按本地时间解释); - 测试:格式与本地字段、`Date.parse` 回环、新旧混合时间窗、usage 行解析。 验证:定向 suite 49/49、`npm run typecheck`、`npm run build`(dist 导入与 外部依赖检查 OK);时区矩阵(Shanghai/UTC/New_York/Kathmandu +05:45/ St_Johns -02:30)日志与 `date` 同刻;真实 `dist` 起代理在隔离 XDG 下三个 时区 e2e,日志文件时间与系统时间一致。全量回归以远程 CI 为准。 --- src/acp-cache-diff.ts | 2 +- src/logger.ts | 12 ++++++++-- src/web/logs-query.ts | 4 +++- tests/logger-local-time.test.ts | 42 +++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 tests/logger-local-time.test.ts diff --git a/src/acp-cache-diff.ts b/src/acp-cache-diff.ts index d01d191dce..6fd8ac1e35 100644 --- a/src/acp-cache-diff.ts +++ b/src/acp-cache-diff.ts @@ -396,7 +396,7 @@ export function compareWires(aBody: Buffer, bBody: Buffer): WireRel { export interface UsageSample { ts: number; input: number; cached: number; } -const USAGE_LINE_RE = /^(\d{4}-\d{2}-\d{2}T[\d:.]+Z?) \[[a-z]+\] \[([^\]]+)\] (?:\[plugin\] )?\[acp-usage\](?: round \d+)? input=(\d+) cached=(\d+)/; +const USAGE_LINE_RE = /^(\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:\d{2})?) \[[a-z]+\] \[([^\]]+)\] (?:\[plugin\] )?\[acp-usage\](?: round \d+)? input=(\d+) cached=(\d+)/; export function parseUsageLog(file: string): Map { const bySession = new Map(); diff --git a/src/logger.ts b/src/logger.ts index 8db5894918..fae60efcc5 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -261,7 +261,7 @@ function warnReopenFailed(err: unknown): void { } if (!stderrDead) { try { - process.stderr.write(`${new Date().toISOString()} [warn] ${msg}\n`); + process.stderr.write(`${logTimestamp()} [warn] ${msg}\n`); } catch { /* stderr gone */ } } } @@ -306,6 +306,14 @@ export function configureLogger(file?: string): string | undefined { return file; } +/** Line timestamp: the system's LOCAL wall-clock time, no zone suffix + * (`2026-10-24T19:19:02.681`) — same shape as the old UTC stamp minus the `Z`, + * so log lines read exactly like `date` on this machine. */ +export function logTimestamp(d: Date = new Date()): string { + const p = (n: number, w = 2): string => String(n).padStart(w, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}.${p(d.getMilliseconds(), 3)}`; +} + /** Log a line to file + stderr. */ export const log: Logger = (level, msg) => { if (capture) { @@ -316,7 +324,7 @@ export const log: Logger = (level, msg) => { } } const safe = maskIpsInText(redactSecretsInText(msg)); - const ts = new Date().toISOString(); + const ts = logTimestamp(); const sess = sessionCtx.getStore(); const head = `${ts} [${level}]${sess ? ` [sess=${sess}]` : ""} [v=${VERSION}]`; // One prefix per PHYSICAL line (see header doc): multi-line payloads keep diff --git a/src/web/logs-query.ts b/src/web/logs-query.ts index b9dca0c1f7..5e72dd54e4 100644 --- a/src/web/logs-query.ts +++ b/src/web/logs-query.ts @@ -37,7 +37,9 @@ interface LogQueryResult { isMatch?: boolean[]; } -const TS_RE = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)/; +// Bare local-time stamps (current format) and the older `Z` / offset forms all +// must parse: one log file outlives a format change. +const TS_RE = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)/; function parseTs(line: string): number { const m = TS_RE.exec(line); diff --git a/tests/logger-local-time.test.ts b/tests/logger-local-time.test.ts new file mode 100644 index 0000000000..baac0217e2 --- /dev/null +++ b/tests/logger-local-time.test.ts @@ -0,0 +1,42 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { logTimestamp } from "../src/logger.ts"; +import { queryLogLines } from "../src/web/logs-query.ts"; +import { parseUsageLog } from "../src/acp-cache-diff.ts"; + +test("logTimestamp: system local wall clock, no zone suffix", () => { + const d = new Date(2026, 9, 24, 19, 19, 2, 681); + const ts = logTimestamp(d); + assert.match(ts, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}$/); + // Local fields, exactly what `date` prints — not the UTC fields. + assert.equal(ts.slice(0, 19), "2026-10-24T19:19:02"); + assert.equal(ts.slice(11, 19), [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":")); + // A bare stamp reads back as local time, so it round-trips on this machine. + assert.equal(Date.parse(ts), d.getTime()); +}); + +test("logs-query: window selection parses bare local stamps (and old Z stamps)", () => { + const zone = new Date(2026, 9, 24, 12, 0, 0, 0); + const local = Array.from({ length: 5 }, (_, i) => `${logTimestamp(new Date(zone.getTime() + i * 60_000))} [info] ${i === 1 ? "needle" : `noise-${i}`}`); + // ±90s around the minute-1 hit → rows 0,1,2 (rows are one minute apart). + assert.deepEqual(queryLogLines(local, "needle", { ctx: 0, winSec: 90, n: 100 }).lines, local.slice(0, 3)); + // Rotated-file stamps stay Z; they must still parse into the same window. + const legacy = ["2026-09-24T14:32:05.123Z [info] needle-a", "2026-09-24T14:32:40.000Z [info] noise-legacy", "2026-09-24T14:33:01.000Z [info] needle-b"]; + assert.deepEqual(queryLogLines(legacy, "needle", { ctx: 0, winSec: 30, n: 100 }).lines, legacy); +}); + +test("acp-cache-diff: usage lines with a bare local stamp still parse", () => { + const dir = mkdtempSync(join(tmpdir(), "bili-log-ts-")); + try { + const file = join(dir, "bili.log"); + const ts = logTimestamp(new Date(2026, 9, 24, 12, 0, 0, 0)); + writeFileSync(file, `${ts} [info] [ses_a] [acp-usage] input=1000 cached=900 (cache hit 90%)\n`); + const bySession = parseUsageLog(file); + assert.deepEqual(bySession.get("ses_a"), [{ ts: Date.parse(ts), input: 1000, cached: 900 }]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});