Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(log): use local timezone for desktop logs (#2830)

author.zero76eab8856f12
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<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");
+ });
+});
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());