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
This commit is contained in:
author.zero authored and GitHub committed 2026-07-08 11:18:52 +08:00
1 parent 15d4dc6e2e
commit 76eab8856f
3 files changed
+143 -4

No files matched your search

@@ -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<string, string>();
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");
});
});
+26 -3
View File
@@ -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({