From 846c2af02b6d432894df1ee09e2eb21995e29b38 Mon Sep 17 00:00:00 2001 From: Manav Rathi Date: Wed, 27 Mar 2024 15:10:35 +0530 Subject: [PATCH] Outline a potential approach --- desktop/src/main/log.ts | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/desktop/src/main/log.ts b/desktop/src/main/log.ts index 014465df1..320ff464a 100644 --- a/desktop/src/main/log.ts +++ b/desktop/src/main/log.ts @@ -32,3 +32,60 @@ export function logErrorSentry( console.log(error, { msg, info }); } } + +const logError1 = (message: string, e?: unknown) => { + if (e === undefined || e === null) { + log.error(message); + return; + } + + let es: string; + if (e instanceof Error) { + // In practice, we expect ourselves to be called with Error objects, so + // this is the happy path so to say. + es = `${e.name}: ${e.message}\n${e.stack}`; + } else { + // For the rest rare cases, use the default string serialization of e. + es = String(e); + } + + log.error(`${message}: ${es}`); +}; + +const logInfo = (message: string) => { + log.info(message); +}; + +const logDebug = (message: () => string) => { + if (isDev) log.debug(() => message); +}; + +export default { + /** + * Log an error message with an optional associated error object. + * + * {@link e} is generally expected to be an `instanceof Error` but it can be + * any arbitrary object too that we obtain, say, when in a try-catch + * handler. + * + * The log is written to disk, and is also printed to the console. + */ + error: logError1, + /** + * Log a message. + * + * The log is written to disk, and is also printed to the console. + */ + info: logInfo, + /** + * Log a debug message. + * + * The log is not written to disk. And it is printed to the console only on + * development builds. + * + * To avoid running unnecessary code in release builds, this function takes + * a function to call to get the log message instead of directly taking the + * message. This function will only be called in development builds. + */ + debug: logDebug, +};