Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Keep upload diagnostics explicit without log filtering

Anand Baburajan75b30e5920ad
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index d35875ad71..3af45a77b5 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -86,6 +86,26 @@ impl From<Error> for JsValue {
if let Some(name) = error.name() {
js_error.set_name(name);
}
+ if let Error::Space(ente_space::Error::Http(http_error)) = &error
+ && let Some(status) = http_error.status_code()
+ {
+ let _ = js_sys::Reflect::set(&js_error, &"status".into(), &status.into());
+ }
+ let code = match &error {
+ Error::Space(ente_space::Error::Http(ente_core::http::Error::Api { code, .. })) => {
+ Some(code.as_str())
+ }
+ Error::Space(ente_space::Error::Http(ente_core::http::Error::Network(_))) => {
+ Some("network_error")
+ }
+ Error::Space(ente_space::Error::Http(ente_core::http::Error::Parse(_))) => {
+ Some("response_parse_error")
+ }
+ _ => error.name(),
+ };
+ if let Some(code) = code {
+ let _ = js_sys::Reflect::set(&js_error, &"code".into(), &code.into());
+ }
js_error.into()
}
}
diff --git a/web/apps/space/src/pages/_app.tsx b/web/apps/space/src/pages/_app.tsx
index b1350b3c88..01be0a86b1 100644
--- a/web/apps/space/src/pages/_app.tsx
+++ b/web/apps/space/src/pages/_app.tsx
@@ -8,7 +8,6 @@ import "configure-zod";
import { CustomHead } from "ente-base/components/Head";
import { useSetupLogs } from "ente-base/components/utils/hooks-app";
import { shareTheme } from "ente-base/components/utils/theme";
-import { setLogSanitizer } from "ente-base/log";
import { captureSpacePWAInstallPrompt } from "hooks/use-pwa-install-prompt";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
@@ -27,11 +26,8 @@ import {
spaceTextMuted,
} from "styles/colors";
import "styles/globals.css";
-import { sanitizeSpaceLog } from "utils/logs";
import { spacePageTitle } from "utils/page-titles";
-setLogSanitizer(sanitizeSpaceLog);
-
const interFontURL = new URL(
"@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
import.meta.url,
@@ -103,7 +99,7 @@ const spaceTheme = createTheme(
);
const App: React.FC<AppProps> = ({ Component, pageProps }) => {
- useSetupLogs();
+ useSetupLogs({ disableDiskLogs: true });
const router = useRouter();
const publicProfileManifest = router.pathname == "/profile-link";
diff --git a/web/apps/space/src/screens/SettingsScreen.tsx b/web/apps/space/src/screens/SettingsScreen.tsx
index 80ca67eb30..399a8639a8 100644
--- a/web/apps/space/src/screens/SettingsScreen.tsx
+++ b/web/apps/space/src/screens/SettingsScreen.tsx
@@ -37,7 +37,6 @@ import {
spaceTextMuted,
} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
-import { sanitizeSpaceLog } from "utils/logs";
const green = "#08C225";
const textBase = spaceText;
@@ -563,7 +562,7 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({
label="Download logs"
onClick={() =>
saveStringAsFile(
- savedLogs(sanitizeSpaceLog),
+ savedLogs(),
`ente-space-logs-${Date.now()}.txt`,
)
}
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index de3b924053..95c424af1e 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -2,6 +2,7 @@ import type { FriendProfile } from "data/friends";
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { isNamedError } from "ente-base/error";
import log from "ente-base/log";
+import { logToDisk } from "ente-base/log-web";
import { apiOrigin } from "ente-base/origins";
import type { UploadedPostAsset } from "ente-space-wasm";
import {
@@ -1230,9 +1231,11 @@ export const createCurrentMediaPost = async ({
}
return session.postId;
} catch (error) {
- log.error(
- `Space post upload failed ${JSON.stringify({ requestId: session.requestId, stage, itemIndex, itemCount: images.length, bytes })}`,
- error,
+ const uploadError = error as
+ | (Error & { status?: number; code?: string })
+ | undefined;
+ logToDisk(
+ `[error] Space post upload failed ${JSON.stringify({ requestId: session.requestId, stage, itemIndex, itemCount: images.length, bytes, status: uploadError?.status, code: uploadError?.code })}`,
);
throw error;
} finally {
diff --git a/web/apps/space/src/state/AppStateProvider.tsx b/web/apps/space/src/state/AppStateProvider.tsx
index 4bc7fe7e46..199ba650db 100644
--- a/web/apps/space/src/state/AppStateProvider.tsx
+++ b/web/apps/space/src/state/AppStateProvider.tsx
@@ -1,5 +1,6 @@
import { retryAsyncOperation } from "ente-base/http";
import log from "ente-base/log";
+import { logToDisk } from "ente-base/log-web";
import React, {
useCallback,
useEffect,
@@ -212,9 +213,8 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
image.rotationDegrees,
);
} catch (error) {
- log.error(
- `Space post preparation failed request=${session.requestId} item=${index + 1}/${images.length} type=${image.file.type} bytes=${image.file.size}`,
- error,
+ logToDisk(
+ `[error] Space post preparation failed request=${session.requestId} item=${index + 1}/${images.length} media=${image.video ? "video" : "photo"} bytes=${image.file.size}`,
);
throw error;
}
@@ -229,8 +229,8 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
});
const posted = { ...publication.post, postId };
postUploadsRef.current.delete(localPostId);
- log.info(
- `Space post published request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
+ logToDisk(
+ `[info] Space post published request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
);
if (profileRef.current?.spaceId != spaceId)
return posted;
@@ -315,9 +315,8 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
void readback();
return posted;
} catch (error) {
- log.error(
- `Space post failed request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
- error,
+ logToDisk(
+ `[error] Space post failed request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
);
failLocalFeedPost(setLocalFeedPosts, localPostId);
if (postPublishGenerationRef.current == generation) {
diff --git a/web/apps/space/src/utils/logs.ts b/web/apps/space/src/utils/logs.ts
deleted file mode 100644
index 606c77b406..0000000000
--- a/web/apps/space/src/utils/logs.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-const events = [
- "Space post upload failed",
- "Space post preparation failed",
- "Space post failed",
- "Space post published",
- "Failed to publish space post",
- "Failed to refresh a published post",
- "Failed to prepare post preview",
- "Failed to prepare edited post photos",
- "WebCodecs export failed, using FFmpeg",
- "[wasm] ffmpeg command failed",
- "[wasm] ffprobe command failed",
- "[rust] ente_core::http: retrying",
- "Failed to load space feed",
- "Failed to load space profile",
- "Failed to decrypt Space browser session",
- "Space login email verification failed",
- "Space signup verification failed",
- "Space 2FA verification failed",
- "Space passkey verification failed",
- "Unhandled error",
- "Unhandled promise rejection",
- "Application error",
- "Application warning",
- "Application event",
-];
-
-const errorCodes = [
- "SPACE_UPLOAD_LIMIT_REACHED",
- "post_limit_reached",
- "UNAUTHORIZED",
- "PERMISSION_DENIED",
- "BAD_REQUEST",
- "NOT_FOUND",
- "CONFLICT",
- "RATE_LIMIT_EXCEEDED",
-];
-
-const errorReasons = [
- "error sending request",
- "Failed to fetch",
- "Load failed",
- "NetworkError",
- "TimeoutError",
- "AbortError",
- "QuotaExceededError",
- "NotSupportedError",
- "EncodingError",
- "SecurityError",
- "SpaceImageTypeError",
- "SpaceImageSizeError",
- "Only photos can be uploaded.",
- "This photo is too large. Try a smaller one.",
- "Could not decode image",
- "Could not encode image",
- "Could not create image canvas",
- "Invalid image dimensions",
- "This browser can't preview this video.",
- "The video took too long to load.",
- "This video has no readable duration.",
- "Couldn't prepare the video cover.",
- "Choose a video segment of up to 10 seconds.",
- "This video is too large. Try a shorter trim.",
- "Couldn't export a video within 10 seconds.",
- "Couldn't read video packets",
- "Couldn't prepare the video frames",
- "Video export is missing frames",
- "space post limit reached",
- "missing secret key material",
- "TypeError",
- "RangeError",
- "SyntaxError",
-];
-
-const uploadFields: [string, RegExp][] = [
- [
- "request",
- /(?:request=|"requestId":")([a-f\d]{8}-[a-f\d]{4}-4[a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12})\b/i,
- ],
- [
- "stage",
- /(?:stage=|"stage":")(prepare|upload-preview|upload-video|create-post)\b/,
- ],
- ["attempt", /\battempt=(\d{1,6})\b/],
- ["elapsedMs", /\belapsedMs=(\d{1,12})\b/],
- ["item", /\bitem=(\d{1,2}\/\d{1,2})\b/],
- ["itemIndex", /(?:itemIndex=|"itemIndex":)(\d{1,2})\b/],
- ["itemCount", /(?:itemCount=|"itemCount":)(\d{1,2})\b/],
- ["bytes", /(?:bytes=|"bytes":)(\d{1,12})\b/],
- [
- "type",
- /\btype=((?:image\/(?:jpeg|jpg|png|webp|heic|heif)|video\/(?:mp4|quicktime|webm)))(?=\s|$)/,
- ],
-];
-
-export const sanitizeSpaceLog = (message: string) => {
- const level = /^\[(error|warn|info)\] /.exec(message)?.[1] ?? "info";
- const body = message.replace(/^\[(error|warn|info)\] /, "");
- const event =
- events.find((event) => body.startsWith(event)) ??
- (level == "error"
- ? "Application error"
- : level == "warn"
- ? "Application warning"
- : "Application event");
- const details = [`[${level}] ${event}`];
- if (event.startsWith("Space post ")) {
- const metadata = body.split(": ")[0]!;
- for (const [field, pattern] of uploadFields) {
- const value = pattern.exec(metadata)?.[1];
- if (value) details.push(`${field}=${value}`);
- }
- }
- if (event == "[rust] ente_core::http: retrying") {
- const delay =
- /(?:retrying in |delaySeconds=)(2|5|10|30|120)(?:s|\b)/.exec(
- body,
- )?.[1];
- if (delay) details.push(`delaySeconds=${delay}`);
- }
- const exitCode =
- /(?:ffmpeg command failed with exit code |ffprobe command failed with exit code |exitCode=)(-?\d{1,3})\b/.exec(
- body,
- )?.[1];
- if (exitCode) details.push(`exitCode=${exitCode}`);
- const status = /(?:HTTP |status=)([45]\d{2})\b/.exec(body)?.[1];
- if (status) details.push(`status=${status}`);
- const code = errorCodes.find((code) => body.includes(code));
- if (code) details.push(`code=${code}`);
- const reason = errorReasons.find((reason) => body.includes(reason));
- if (reason) details.push(`reason=${reason}`);
- return details.join(" ");
-};
diff --git a/web/apps/space/tests/logs.test.ts b/web/apps/space/tests/logs.test.ts
deleted file mode 100644
index cfeb7e47f2..0000000000
--- a/web/apps/space/tests/logs.test.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import log, { logToDisk, setLogSanitizer } from "ente-base/log";
-import { savedLogs } from "ente-base/log-web";
-import { afterEach, beforeEach, expect, test, vi } from "vitest";
-import { sanitizeSpaceLog } from "../src/utils/logs";
-
-const requestID = "ed2d1157-f958-489c-aa59-25b49f560b8a";
-
-beforeEach(() => {
- const items = new Map<string, string>();
- vi.stubGlobal("localStorage", {
- getItem: (key: string) => items.get(key) ?? null,
- setItem: (key: string, value: string) => items.set(key, value),
- removeItem: (key: string) => items.delete(key),
- });
- vi.spyOn(console, "error").mockImplementation(() => undefined);
- setLogSanitizer(sanitizeSpaceLog);
-});
-
-afterEach(() => {
- setLogSanitizer((message) => message);
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-test("saves upload diagnostics without URLs, credentials, or error payloads", () => {
- const error = new Error(
- "HTTP 429 SPACE_UPLOAD_LIMIT_REACHED at https://api.test/spaces/private-space?token=secret-token [email protected] caption=Family birthday",
- );
- error.stack = `Error: ${error.message}\n at /Users/Alice/holiday.jpg:4:8`;
- log.error(
- `Space post upload failed ${JSON.stringify({ requestId: requestID, stage: "upload-video", itemIndex: 2, itemCount: 3, bytes: 4096 })}`,
- error,
- );
- const expected = `[error] Space post upload failed request=${requestID} stage=upload-video itemIndex=2 itemCount=3 bytes=4096 status=429 code=SPACE_UPLOAD_LIMIT_REACHED`;
- const entries = JSON.parse(localStorage.getItem("logs")!) as {
- logs: { logLine: string }[];
- };
- expect(entries.logs.map((entry) => entry.logLine)).toEqual([expected]);
- expect(savedLogs(sanitizeSpaceLog).split("] ").slice(1).join("] ")).toBe(
- expected,
- );
-});
-
-test.each([
- "[info] Profile Alice Example [email protected] +1-202-555-0100 uid 12345",
- "[warn] [rust] ente_space::client::profiles: Space profile private-space fell back to public fields: private payload",
- "[info] Starting ente-space-web uid 12345",
- "[error] Unhandled error: private message with a caption and auth token\n at https://space.test/alice?token=secret",
- "[info] [wasm] ffmpeg command failed: /Users/Alice/private-video.mp4",
-])("does not retain arbitrary personal data in %s", (message) => {
- logToDisk(message);
- expect(savedLogs()).not.toMatch(
- /Alice|alice|example\.test|202-555|12345|private|secret|https:/,
- );
-});
-
-test("filters legacy entries and unexpected records again on download", () => {
- localStorage.setItem(
- "logs",
- JSON.stringify({
- logs: [
- {
- timestamp: 0,
- logLine:
- "[error] Failed to publish space post: Error: HTTP 503 at https://api.test/spaces/private-space/posts?token=secret",
- },
- { caption: "Family birthday" },
- ],
- }),
- );
- expect(savedLogs(sanitizeSpaceLog)).toBe(
- "[1970-01-01T00:00:00.000Z] [error] Failed to publish space post status=503\n[info] Application event\n[info] Application event",
- );
-});
-
-test.each([
- [
- `[error] Space post failed request=${requestID} attempt=2 elapsedMs=450: TypeError: Failed to fetch`,
- "attempt=2 elapsedMs=450 reason=Failed to fetch",
- ],
- [
- `[error] Space post preparation failed request=${requestID} item=2/3 type=image/jpeg bytes=500: Error: Could not decode image at /Users/Alice/photo.jpg`,
- "item=2/3 bytes=500 type=image/jpeg reason=Could not decode image",
- ],
- [
- "[warn] [rust] ente_core::http: retrying in 5s: HTTP 503 at https://bucket.test/object?signature=secret",
- "delaySeconds=5 status=503",
- ],
- [
- "[error] Space post failed: post_limit_reached: space post limit reached",
- "code=post_limit_reached reason=space post limit reached",
- ],
- [
- "[info] [wasm] ffmpeg command failed with exit code 1: -i /Users/Alice/private.mp4",
- "exitCode=1",
- ],
-])(
- "keeps useful diagnostics and remains safe on repeated filtering",
- (message, expected) => {
- const sanitized = sanitizeSpaceLog(message);
- expect(sanitized).toContain(expected);
- expect(sanitizeSpaceLog(sanitized)).toBe(sanitized);
- expect(sanitized).not.toMatch(/Alice|photo\.jpg|https:|secret/);
- },
-);
-
-test("does not extract upload metadata from exception text", () => {
- expect(
- sanitizeSpaceLog(
- `[error] Space post failed: TypeError: request=${requestID} bytes=2025550100`,
- ),
- ).toBe("[error] Space post failed reason=TypeError");
-});
-
-test("leaves shared logging unchanged when no Space filter is configured", () => {
- setLogSanitizer((message) => message);
- logToDisk("[info] A Photos diagnostic");
- expect(savedLogs()).toContain("[info] A Photos diagnostic");
-});
diff --git a/web/apps/space/tests/post-publication.test.ts b/web/apps/space/tests/post-publication.test.ts
index 0733dc128f..426eeb682c 100644
--- a/web/apps/space/tests/post-publication.test.ts
+++ b/web/apps/space/tests/post-publication.test.ts
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
release: vi.fn(),
cacheMedia: vi.fn(),
cachePost: vi.fn(),
- logError: vi.fn(),
+ logToDisk: vi.fn(),
}));
vi.mock("services/profile", () => ({
@@ -33,9 +33,8 @@ vi.mock("services/media-cache", () => ({
`${spaceId}:${key}`,
clearSpaceMediaURLCache: vi.fn(),
}));
-vi.mock("ente-base/log", () => ({
- default: { warn: vi.fn(), error: mocks.logError },
-}));
+vi.mock("ente-base/log", () => ({ default: { warn: vi.fn() } }));
+vi.mock("ente-base/log-web", () => ({ logToDisk: mocks.logToDisk }));
const file = new File(["photo"], "photo.webp", { type: "image/webp" });
const images = [{ file, width: 1200, height: 800, thumbHash: "hash" }];
@@ -162,9 +161,8 @@ test("retry keeps completed photos and the post request ID", async () => {
await expect(createCurrentMediaPost(request)).rejects.toThrow("HTTP 503");
const requestId = session.requestId;
expect(mocks.ctx.createMediaPost).not.toHaveBeenCalled();
- expect(mocks.logError).toHaveBeenCalledWith(
+ expect(mocks.logToDisk).toHaveBeenCalledWith(
expect.stringContaining('"stage":"upload-preview","itemIndex":2'),
- expect.any(Error),
);
expect(await createCurrentMediaPost(request)).toBe(501);
expect(mocks.ctx.uploadPostPhotoAsset).toHaveBeenCalledTimes(3);
@@ -211,3 +209,35 @@ test("retry after a lost creation response keeps the request ID and uploaded ass
mocks.ctx.createMediaPost.mock.calls[0],
);
});
+
+test("records upload facts without saving the error, file name, caption, or space ID", async () => {
+ const error = Object.assign(
+ new Error(
+ "HTTP 429 at https://api.test/spaces/private-space?token=secret [email protected]",
+ ),
+ { status: 429, code: "SPACE_UPLOAD_LIMIT_REACHED" },
+ );
+ error.stack = `${error.message}\n at /Users/Alice/family.jpg:4:8`;
+ mocks.ctx.uploadPostPhotoAsset.mockRejectedValueOnce(error);
+ const session: SpacePostUploadSession = { uploads: [] };
+ await expect(
+ createCurrentMediaPost({
+ images: [
+ {
+ ...images[0]!,
+ file: new File(["photo"], "Alice-family.jpg", {
+ type: "image/jpeg",
+ }),
+ },
+ ],
+ caption: "Family birthday",
+ spaceId: "private-space",
+ session,
+ }),
+ ).rejects.toBe(error);
+ expect(mocks.logToDisk.mock.calls).toEqual([
+ [
+ `[error] Space post upload failed ${JSON.stringify({ requestId: session.requestId, stage: "upload-preview", itemIndex: 1, itemCount: 1, bytes: 5, status: 429, code: "SPACE_UPLOAD_LIMIT_REACHED" })}`,
+ ],
+ ]);
+});
diff --git a/web/apps/space/tests/post-upload.test.ts b/web/apps/space/tests/post-upload.test.ts
index 987ab0c9f2..0b87ddd328 100644
--- a/web/apps/space/tests/post-upload.test.ts
+++ b/web/apps/space/tests/post-upload.test.ts
@@ -343,13 +343,65 @@ test("preserves the unfinished upload limit code without retrying it", async ()
try {
await expect(
createPhotoPost("test-space", [photo(0)], "Caption"),
- ).rejects.toThrow("SPACE_UPLOAD_LIMIT_REACHED");
+ ).rejects.toMatchObject({
+ status: 429,
+ code: "SPACE_UPLOAD_LIMIT_REACHED",
+ });
expect(attempts).toBe(1);
} finally {
ctx.free();
}
});
+test.each([503, "network"] as const)(
+ "exposes structured diagnostics after exhausting %s upload retries",
+ async (failure) => {
+ vi.useFakeTimers();
+ const { ctx, createPhotoPost } = await uploadFixture(
+ false,
+ (request) => {
+ if (request.method != "PUT") return undefined;
+ if (failure == "network")
+ return Promise.reject(new TypeError("Failed to fetch"));
+ return Promise.resolve(new Response("", { status: failure }));
+ },
+ );
+ try {
+ const rejection = expect(
+ createPhotoPost("test-space", [photo(0)], "Caption"),
+ ).rejects.toMatchObject(
+ failure == "network"
+ ? { code: "network_error" }
+ : { status: 503 },
+ );
+ await vi.runAllTimersAsync();
+ await rejection;
+ } finally {
+ ctx.free();
+ }
+ },
+);
+
+test("exposes the permanent post limit as a diagnostic code", async () => {
+ const { ctx, createPhotoPost } = await uploadFixture(false, (request) => {
+ if (request.method != "POST" || !request.url.endsWith("/posts"))
+ return undefined;
+ return Promise.resolve(
+ Response.json({ code: "CONFLICT" }, { status: 409 }),
+ );
+ });
+ try {
+ await expect(
+ createPhotoPost("test-space", [photo(0)], "Caption"),
+ ).rejects.toMatchObject({
+ name: "post_limit_reached",
+ code: "post_limit_reached",
+ });
+ } finally {
+ ctx.free();
+ }
+});
+
test.each([0, 11])("rejects %i items before publishing", async (count) => {
const { ctx, calls } = await uploadFixture();
try {
diff --git a/web/packages/base/log-web.ts b/web/packages/base/log-web.ts
index 2fccc6a9f8..4858e86070 100644
--- a/web/packages/base/log-web.ts
+++ b/web/packages/base/log-web.ts
@@ -97,18 +97,15 @@ const logEntries = (): unknown[] => {
return o.logs;
};
-export const savedLogs = (sanitize?: (message: string) => string) =>
- logEntries()
- .map((entry) => formatEntry(entry, sanitize))
- .join("\n");
+export const savedLogs = () => logEntries().map(formatEntry).join("\n");
-const formatEntry = (e: unknown, sanitize?: (message: string) => string) => {
+const formatEntry = (e: unknown) => {
if (e && typeof e == "object" && "timestamp" in e && "logLine" in e) {
const timestamp = e.timestamp;
const logLine = e.logLine;
if (typeof timestamp == "number" && typeof logLine == "string") {
- return `[${new Date(timestamp).toISOString()}] ${sanitize?.(logLine) ?? logLine}`;
+ return `[${new Date(timestamp).toISOString()}] ${logLine}`;
}
}
- return sanitize?.(String(e)) ?? String(e);
+ return String(e);
};
diff --git a/web/packages/base/log.ts b/web/packages/base/log.ts
index 0ad7ee3807..6c7f4cb08c 100644
--- a/web/packages/base/log.ts
+++ b/web/packages/base/log.ts
@@ -4,16 +4,10 @@ import { logToDisk as webLogToDisk } from "./log-web";
import { workerBridge } from "./worker/worker-bridge";
let shouldLogToDisk = true;
-let logSanitizer: ((message: string) => string) | undefined;
export const disableDiskLogs = () => (shouldLogToDisk = false);
-export const setLogSanitizer = (sanitize: (message: string) => string) => {
- logSanitizer = sanitize;
-};
-
export const logToDisk = (message: string) => {
- message = logSanitizer?.(message) ?? message;
const electron = globalThis.electron;
if (electron) electron.logToDisk(message);
else if (inWorker()) workerLogToDisk(message);