From 76eab8856f12b20e9815ee9990469c25435ace35 Mon Sep 17 00:00:00 2001 From: "author.zero" <1090863704@qq.com> Date: Wed, 8 Jul 2026 11:18:52 +0800 Subject: [PATCH] fix(log): use local timezone for desktop logs (#2830) * fix: use local timezone for desktop logs * test: cover debug log local timestamps * style: format desktop log formatter --- .../lib/backend/__tests__/debugLog.spec.ts | 102 ++++++++++++++++++ apps/desktop/src/lib/backend/debugLog.ts | 29 ++++- src-tauri/src/lib.rs | 16 ++- 3 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts diff --git a/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts b/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts new file mode 100644 index 0000000000..b68b10db96 --- /dev/null +++ b/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { appendDebugLog, formatLocalTimestamp, formatLocalTimestampForFilename, formatLocalTimezoneOffset, getDebugLogText, padNumber } from "@/lib/backend/debugLog"; + +class MemoryStorage implements Storage { + private data = new Map(); + + get length() { + return this.data.size; + } + + clear() { + this.data.clear(); + } + + getItem(key: string) { + return this.data.get(key) ?? null; + } + + key(index: number) { + return [...this.data.keys()][index] ?? null; + } + + removeItem(key: string) { + this.data.delete(key); + } + + setItem(key: string, value: string) { + this.data.set(key, value); + } +} + +const DEBUG_LOG_ENABLED_KEY = "dbx-debug-logging-enabled"; + +let originalLocalStorage: PropertyDescriptor | undefined; + +function expectedLocalOffset(date: Date): string { + const offsetMinutes = -date.getTimezoneOffset(); + const sign = offsetMinutes >= 0 ? "+" : "-"; + const absoluteMinutes = Math.abs(offsetMinutes); + return `${sign}${String(Math.floor(absoluteMinutes / 60)).padStart(2, "0")}:${String(absoluteMinutes % 60).padStart(2, "0")}`; +} + +beforeEach(() => { + originalLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: new MemoryStorage(), + }); +}); + +afterEach(() => { + vi.useRealTimers(); + if (originalLocalStorage) Object.defineProperty(globalThis, "localStorage", originalLocalStorage); + else Reflect.deleteProperty(globalThis, "localStorage"); +}); + +describe("debug log local timestamps", () => { + it("pads date and time parts", () => { + expect(padNumber(7)).toBe("07"); + expect(padNumber(35)).toBe("35"); + expect(padNumber(8, 3)).toBe("008"); + }); + + it("formats timezone offsets in RFC 3339 style", () => { + const east = new Date(0); + const west = new Date(0); + vi.spyOn(east, "getTimezoneOffset").mockReturnValue(-480); + vi.spyOn(west, "getTimezoneOffset").mockReturnValue(420); + + expect(formatLocalTimezoneOffset(east)).toBe("+08:00"); + expect(formatLocalTimezoneOffset(west)).toBe("-07:00"); + }); + + it("formats local timestamps with milliseconds and timezone", () => { + const date = new Date(2026, 6, 8, 9, 50, 35, 882); + + expect(formatLocalTimestamp(date)).toBe(`2026-07-08T09:50:35.882${expectedLocalOffset(date)}`); + }); + + it("formats Windows-safe filename timestamp tokens", () => { + const date = new Date(2026, 6, 8, 9, 50, 35, 882); + const filenameToken = formatLocalTimestampForFilename(date); + + expect(filenameToken).toBe(`2026-07-08T09-50-35-882${expectedLocalOffset(date).replace(":", "-")}`); + expect(filenameToken).not.toMatch(/[:.]/); + }); + + it("uses local timestamps in exported debug log text", () => { + const date = new Date(2026, 6, 8, 9, 50, 35, 882); + const timestamp = formatLocalTimestamp(date); + vi.useFakeTimers(); + vi.setSystemTime(date); + localStorage.setItem(DEBUG_LOG_ENABLED_KEY, "1"); + + appendDebugLog("info", "hello"); + + const text = getDebugLogText(); + expect(text).toContain(`Exported: ${timestamp}`); + expect(text).toContain(`[${timestamp}] [INFO] hello`); + expect(text).not.toContain(".882Z"); + }); +}); diff --git a/apps/desktop/src/lib/backend/debugLog.ts b/apps/desktop/src/lib/backend/debugLog.ts index 76ba18126a..9c7bf8cb47 100644 --- a/apps/desktop/src/lib/backend/debugLog.ts +++ b/apps/desktop/src/lib/backend/debugLog.ts @@ -81,11 +81,34 @@ function formatArgs(args: unknown[]): string { return message.length > MAX_TEXT_LENGTH ? `${message.slice(0, MAX_TEXT_LENGTH)}...` : message; } +// Pads date/time parts to keep timestamps width-stable. +export function padNumber(value: number, length = 2): string { + return String(value).padStart(length, "0"); +} + +// Formats the local UTC offset in RFC 3339 style. +export function formatLocalTimezoneOffset(date: Date): string { + const offsetMinutes = -date.getTimezoneOffset(); + const sign = offsetMinutes >= 0 ? "+" : "-"; + const absoluteMinutes = Math.abs(offsetMinutes); + return `${sign}${padNumber(Math.floor(absoluteMinutes / 60))}:${padNumber(absoluteMinutes % 60)}`; +} + +// Formats a local timestamp with milliseconds and timezone. +export function formatLocalTimestamp(date = new Date()): string { + return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}T${padNumber(date.getHours())}:${padNumber(date.getMinutes())}:${padNumber(date.getSeconds())}.${padNumber(date.getMilliseconds(), 3)}${formatLocalTimezoneOffset(date)}`; +} + +// Converts the local timestamp into a Windows-safe filename token. +export function formatLocalTimestampForFilename(date = new Date()): string { + return formatLocalTimestamp(date).replace(/[:.]/g, "-"); +} + export function appendDebugLog(level: DebugLogLevel, ...args: unknown[]) { if (!isDebugLoggingEnabled()) return; const entries = readEntries(); entries.push({ - timestamp: new Date().toISOString(), + timestamp: formatLocalTimestamp(), level, message: formatArgs(args), }); @@ -111,14 +134,14 @@ export function clearDebugLogs() { export function getDebugLogText(): string { const entries = readEntries(); - const header = [`DBX debug log`, `Exported: ${new Date().toISOString()}`, `User agent: ${navigator.userAgent}`, `Platform: ${navigator.platform}`, `Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown"}`, ""]; + const header = [`DBX debug log`, `Exported: ${formatLocalTimestamp()}`, `User agent: ${navigator.userAgent}`, `Platform: ${navigator.platform}`, `Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown"}`, ""]; const body = entries.map((entry) => `[${entry.timestamp}] [${entry.level.toUpperCase()}] ${entry.message}`); return [...header, ...body].join("\n"); } export async function downloadDebugLogs() { const text = await getDebugLogBundleText(); - const filename = `dbx-debug-log-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`; + const filename = `dbx-debug-log-${formatLocalTimestampForFilename()}.txt`; if (typeof window !== "undefined" && isTauriRuntimeLike()) { const [{ save }, { writeTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]); const path = await save({ diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6ab89f4559..e9e3161155 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -656,7 +656,21 @@ pub fn run() { s }); let desktop_settings = tauri::async_runtime::block_on(storage.load_desktop_settings()).unwrap_or_default(); - app.handle().plugin(tauri_plugin_log::Builder::default().level(log::LevelFilter::Debug).build())?; + app.handle().plugin( + tauri_plugin_log::Builder::default() + .timezone_strategy(tauri_plugin_log::TimezoneStrategy::UseLocal) + .format(|out, message, record| { + out.finish(format_args!( + "[{}][{}][{}] {}", + chrono::Local::now().format("%Y-%m-%d][%H:%M:%S%.3f"), + record.level(), + record.target(), + message + )); + }) + .level(log::LevelFilter::Debug) + .build(), + )?; apply_debug_log_level(desktop_settings.debug_logging_enabled); eprintln!("[STARTUP] storage ready in {:?}", t.elapsed());