Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

refactor: Standardize logging on log levels with renderer IPC and .env refresh

Gabriel Steinb0c48b6ee37c
diff --git a/CLAUDE.md b/CLAUDE.md
index 00ee62316..8a166d57f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -216,7 +216,7 @@ Settings stored in localStorage with these keys:
### 9. Debug Mode
-Enable with `--debug` flag or `OPENWHISPR_DEBUG=true`:
+Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `.env`):
- Logs saved to platform-specific app data directory
- Comprehensive logging of audio pipeline
- FFmpeg path resolution details
@@ -314,4 +314,4 @@ Enable with `--debug` flag or `OPENWHISPR_DEBUG=true`:
- Multi-language UI
- Cloud model selection
- Batch transcription
-- Export formats beyond clipboard
\ No newline at end of file
+- Export formats beyond clipboard
diff --git a/DEBUG.md b/DEBUG.md
index 0971485f6..260556c16 100644
--- a/DEBUG.md
+++ b/DEBUG.md
@@ -5,34 +5,50 @@
When experiencing issues like "no audio detected", you can enable verbose debug logging to help diagnose the problem.
### Method 1: Command Line Flag
-Run the app with the `--debug` flag:
+Run the app with the `--log-level=debug` flag:
```bash
# macOS
-/Applications/OpenWhispr.app/Contents/MacOS/OpenWhispr --debug
+/Applications/OpenWhispr.app/Contents/MacOS/OpenWhispr --log-level=debug
# Windows
-OpenWhispr.exe --debug
+OpenWhispr.exe --log-level=debug
```
### Method 2: Environment Variable
-Set the `OPENWHISPR_DEBUG` environment variable:
+Set the `OPENWHISPR_LOG_LEVEL=debug` environment variable:
```bash
# macOS/Linux
-export OPENWhISPR_DEBUG=true
+export OPENWHISPR_LOG_LEVEL=debug
open /Applications/OpenWhispr.app
# Windows
-set OPENWhISPR_DEBUG=true
+set OPENWHISPR_LOG_LEVEL=debug
OpenWhispr.exe
```
+You can also put `OPENWHISPR_LOG_LEVEL=debug` in the app's `.env` file and restart:
+
+- **macOS**: `~/Library/Application Support/OpenWhispr/.env`
+- **Windows**: `%APPDATA%\OpenWhispr\.env`
+- **Linux**: `~/.config/OpenWhispr/.env`
## Finding the Debug Logs
When debug mode is enabled, logs are saved to:
-- **macOS**: `~/Library/Application Support/open-whispr/logs/debug-[timestamp].log`
-- **Windows**: `%APPDATA%/open-whispr/logs/debug-[timestamp].log`
-- **Linux**: `~/.config/open-whispr/logs/debug-[timestamp].log`
+- **macOS**: `~/Library/Application Support/OpenWhispr/logs/debug-[timestamp].log`
+- **Windows**: `%APPDATA%\OpenWhispr\logs\debug-[timestamp].log`
+- **Linux**: `~/.config/OpenWhispr/logs/debug-[timestamp].log`
+
+## Log Levels (Quick Guide)
+
+Log levels control how verbose logging is. Setting `--log-level=debug` means you'll see everything at `debug` and above.
+
+- `trace`: very detailed, internal flow (most verbose)
+- `debug`: detailed diagnostics for troubleshooting
+- `info`: normal operational events
+- `warn`: something unexpected, but the app can continue
+- `error`: a failure occurred
+- `fatal`: the app can't continue
## What the Logs Include
@@ -166,5 +182,5 @@ When reporting issues:
## Disabling Debug Mode
Debug mode is disabled by default. To ensure it's off:
-- Don't use the `--debug` flag
-- Unset the environment variable: `unset OPENWHISPR_DEBUG`
\ No newline at end of file
+- Don't use `--log-level=debug`
+- Unset the environment variable: `unset OPENWHISPR_LOG_LEVEL`
diff --git a/WINDOWS_TROUBLESHOOTING.md b/WINDOWS_TROUBLESHOOTING.md
index d34e7ec9e..3b3645901 100644
--- a/WINDOWS_TROUBLESHOOTING.md
+++ b/WINDOWS_TROUBLESHOOTING.md
@@ -103,20 +103,19 @@ Debug mode creates detailed logs for troubleshooting:
### Method 1: Command Line
```batch
cd "C:\Users\YourName\AppData\Local\Programs\OpenWhispr"
-OpenWhispr.exe --debug
+OpenWhispr.exe --log-level=debug
```
### Method 2: Environment Variable
```batch
-set OPENWISPR_DEBUG=true
+set OPENWHISPR_LOG_LEVEL=debug
"C:\Users\YourName\AppData\Local\Programs\OpenWhispr\OpenWhispr.exe"
```
-
-### Method 3: Debug File
-```batch
-echo. > "%APPDATA%\OpenWhispr\ENABLE_DEBUG"
+You can also set it in `%APPDATA%\OpenWhispr\.env`:
+```
+OPENWHISPR_LOG_LEVEL=debug
```
-Then restart OpenWhispr normally.
+Then restart OpenWhispr.
### Find Debug Logs
Logs are saved to: `%APPDATA%\OpenWhispr\logs\`
diff --git a/main.js b/main.js
index 250d6eaf4..917a670b9 100644
--- a/main.js
+++ b/main.js
@@ -21,7 +21,7 @@ process.on("unhandledRejection", (reason, promise) => {
});
// Import helper modules
-const DebugLogger = require("./src/helpers/debugLogger");
+const debugLogger = require("./src/helpers/debugLogger");
const EnvironmentManager = require("./src/helpers/environment");
const WindowManager = require("./src/helpers/windowManager");
const DatabaseManager = require("./src/helpers/database");
@@ -61,6 +61,7 @@ setupProductionPath();
// Initialize managers
const environmentManager = new EnvironmentManager();
+debugLogger.refreshLogLevel();
const windowManager = new WindowManager();
const hotkeyManager = windowManager.hotkeyManager;
const databaseManager = new DatabaseManager();
diff --git a/preload.js b/preload.js
index 43288a4e3..90e3ec52b 100644
--- a/preload.js
+++ b/preload.js
@@ -163,9 +163,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
llamaCppInstall: () => ipcRenderer.invoke("llama-cpp-install"),
llamaCppUninstall: () => ipcRenderer.invoke("llama-cpp-uninstall"),
- // Debug logging for reasoning pipeline
- logReasoning: (stage, details) =>
- ipcRenderer.invoke("log-reasoning", stage, details),
+ getLogLevel: () => ipcRenderer.invoke("get-log-level"),
+ log: (entry) => ipcRenderer.invoke("app-log", entry),
// Remove all listeners for a channel
removeAllListeners: (channel) => {
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index c5d358abf..0278367ee 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -1,24 +1,10 @@
import ReasoningService from "../services/ReasoningService";
import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
+import logger from "../utils/logger";
-const isDebugMode = typeof process !== 'undefined' && (process.env.OPENWHISPR_DEBUG === 'true' || process.env.NODE_ENV === 'development');
const SHORT_CLIP_DURATION_SECONDS = 2.5;
const REASONING_CACHE_TTL = 30000; // 30 seconds
-const debugLogger = {
- logReasoning: async (stage, details) => {
- if (!isDebugMode) return;
-
- if (window.electronAPI?.logReasoning) {
- try {
- await window.electronAPI.logReasoning(stage, details);
- } catch (error) {
- // Silent fail
- }
- }
- }
-};
-
class AudioManager {
constructor() {
@@ -304,7 +290,7 @@ class AudioManager {
}
async processWithReasoningModel(text, model, agentName) {
- debugLogger.logReasoning("CALLING_REASONING_SERVICE", {
+ logger.logReasoning("CALLING_REASONING_SERVICE", {
model,
agentName,
textLength: text.length
@@ -317,7 +303,7 @@ class AudioManager {
const processingTime = Date.now() - startTime;
- debugLogger.logReasoning("REASONING_SERVICE_COMPLETE", {
+ logger.logReasoning("REASONING_SERVICE_COMPLETE", {
model,
processingTimeMs: processingTime,
resultLength: result.length,
@@ -328,7 +314,7 @@ class AudioManager {
} catch (error) {
const processingTime = Date.now() - startTime;
- debugLogger.logReasoning("REASONING_SERVICE_ERROR", {
+ logger.logReasoning("REASONING_SERVICE_ERROR", {
model,
processingTimeMs: processingTime,
error: error.message,
@@ -355,7 +341,7 @@ class AudioManager {
return this.reasoningAvailabilityCache.value;
}
- debugLogger.logReasoning("REASONING_STORAGE_CHECK", {
+ logger.logReasoning("REASONING_STORAGE_CHECK", {
storedValue,
typeOfStoredValue: typeof storedValue,
isTrue: storedValue === "true",
@@ -377,7 +363,7 @@ class AudioManager {
try {
const isAvailable = await ReasoningService.isAvailable();
- debugLogger.logReasoning("REASONING_AVAILABILITY", {
+ logger.logReasoning("REASONING_AVAILABILITY", {
isAvailable,
reasoningEnabled: useReasoning,
finalDecision: useReasoning && isAvailable,
@@ -391,7 +377,7 @@ class AudioManager {
return isAvailable;
} catch (error) {
- debugLogger.logReasoning("REASONING_AVAILABILITY_ERROR", {
+ logger.logReasoning("REASONING_AVAILABILITY_ERROR", {
error: error.message,
stack: error.stack,
});
@@ -408,7 +394,7 @@ class AudioManager {
async processTranscription(text, source) {
const normalizedText = typeof text === "string" ? text.trim() : "";
- debugLogger.logReasoning("TRANSCRIPTION_RECEIVED", {
+ logger.logReasoning("TRANSCRIPTION_RECEIVED", {
source,
textLength: normalizedText.length,
textPreview: normalizedText.substring(0, 100) + (normalizedText.length > 100 ? "..." : ""),
@@ -426,7 +412,7 @@ class AudioManager {
: null;
const useReasoning = await this.isReasoningAvailable();
- debugLogger.logReasoning("REASONING_CHECK", {
+ logger.logReasoning("REASONING_CHECK", {
useReasoning,
reasoningModel,
reasoningProvider,
@@ -437,7 +423,7 @@ class AudioManager {
try {
const preparedText = normalizedText;
- debugLogger.logReasoning("SENDING_TO_REASONING", {
+ logger.logReasoning("SENDING_TO_REASONING", {
preparedTextLength: preparedText.length,
model: reasoningModel,
provider: reasoningProvider
@@ -445,7 +431,7 @@ class AudioManager {
const result = await this.processWithReasoningModel(preparedText, reasoningModel, agentName);
- debugLogger.logReasoning("REASONING_SUCCESS", {
+ logger.logReasoning("REASONING_SUCCESS", {
resultLength: result.length,
resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),
processingTime: new Date().toISOString()
@@ -453,7 +439,7 @@ class AudioManager {
return result;
} catch (error) {
- debugLogger.logReasoning("REASONING_FAILED", {
+ logger.logReasoning("REASONING_FAILED", {
error: error.message,
stack: error.stack,
fallbackToCleanup: true
@@ -462,7 +448,7 @@ class AudioManager {
}
}
- debugLogger.logReasoning("USING_STANDARD_CLEANUP", {
+ logger.logReasoning("USING_STANDARD_CLEANUP", {
reason: useReasoning ? "Reasoning failed" : "Reasoning not enabled"
});
diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.js
index dcbd38f1f..9e96ad442 100644
--- a/src/helpers/debugLogger.js
+++ b/src/helpers/debugLogger.js
@@ -2,32 +2,66 @@ const fs = require("fs");
const path = require("path");
const { app } = require("electron");
+const LOG_LEVELS = {
+ trace: 10,
+ debug: 20,
+ info: 30,
+ warn: 40,
+ error: 50,
+ fatal: 60,
+};
+
+const normalizeLevel = (value) => {
+ if (!value) return null;
+ const lower = String(value).toLowerCase();
+ return Object.prototype.hasOwnProperty.call(LOG_LEVELS, lower) ? lower : null;
+};
+
+const readArgLogLevel = () => {
+ const argv = process.argv || [];
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === "--log-level" && argv[i + 1]) {
+ return argv[i + 1];
+ }
+ if (arg.startsWith("--log-level=")) {
+ return arg.split("=", 2)[1];
+ }
+ }
+ return null;
+};
+
class DebugLogger {
constructor() {
- // Only enable debug mode when explicitly requested
- this.debugMode =
- process.env.OPENWISPR_DEBUG === "true" ||
- process.argv.includes("--debug") ||
- this.checkDebugFile();
+ this.logLevel = this.resolveLogLevel();
+ this.levelValue = LOG_LEVELS[this.logLevel] || LOG_LEVELS.info;
+ this.debugMode = this.isDebugEnabled();
this.logFile = null;
this.logStream = null;
+ this.fileLoggingEnabled = false;
if (this.debugMode) {
- // Create logs directory
+ this.initializeFileLogging();
+ }
+ }
+
+ initializeFileLogging() {
+ if (this.fileLoggingEnabled) return;
+
+ try {
const logsDir = path.join(app.getPath("userData"), "logs");
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir, { recursive: true });
}
- // Create log file with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
this.logFile = path.join(logsDir, `debug-${timestamp}.log`);
- // Create write stream for better performance
this.logStream = fs.createWriteStream(this.logFile, { flags: "a" });
+ this.fileLoggingEnabled = true;
- this.log("πŸš€ Debug logging enabled", `Log file: ${this.logFile}`);
- this.log("System Info:", {
+ this.debug("Debug logging enabled", { logFile: this.logFile });
+ this.info("System Info", {
platform: process.platform,
nodeVersion: process.version,
electronVersion: process.versions.electron,
@@ -36,68 +70,154 @@ class DebugLogger {
resourcesPath: process.resourcesPath,
environment: process.env.NODE_ENV,
});
+ } catch (error) {
+ this.fileLoggingEnabled = false;
+ console.error("Failed to initialize debug logging:", error);
}
}
- log(...args) {
- if (!this.debugMode) return;
+ resolveLogLevel() {
+ const argLevel = normalizeLevel(readArgLogLevel());
+ if (argLevel) {
+ return argLevel;
+ }
- const timestamp = new Date().toISOString();
- const message = args
- .map((arg) =>
- typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
- )
+ const envLevel = normalizeLevel(
+ process.env.OPENWHISPR_LOG_LEVEL || process.env.LOG_LEVEL
+ );
+ if (envLevel) {
+ return envLevel;
+ }
+
+ return "info";
+ }
+
+ refreshLogLevel() {
+ const nextLevel = this.resolveLogLevel();
+ if (nextLevel === this.logLevel) return;
+
+ this.logLevel = nextLevel;
+ this.levelValue = LOG_LEVELS[this.logLevel] || LOG_LEVELS.info;
+ this.debugMode = this.isDebugEnabled();
+
+ if (this.debugMode && !this.fileLoggingEnabled) {
+ this.initializeFileLogging();
+ }
+ }
+
+ getLevel() {
+ return this.logLevel;
+ }
+
+ isDebugEnabled() {
+ return this.levelValue <= LOG_LEVELS.debug;
+ }
+
+ shouldLog(level) {
+ const normalized = normalizeLevel(level) || "info";
+ return LOG_LEVELS[normalized] >= this.levelValue;
+ }
+
+ formatArgs(args) {
+ return args
+ .map((arg) => {
+ if (typeof arg === "object") {
+ try {
+ return JSON.stringify(arg, null, 2);
+ } catch (error) {
+ return String(arg);
+ }
+ }
+ return String(arg);
+ })
.join(" ");
+ }
+
+ formatMeta(meta) {
+ if (meta === undefined) return "";
+ if (typeof meta === "string") return meta;
+ try {
+ return JSON.stringify(meta, null, 2);
+ } catch (error) {
+ return String(meta);
+ }
+ }
- const logLine = `[${timestamp}] ${message}\n`;
+ write(level, message, meta, scope, source) {
+ const normalized = normalizeLevel(level) || "info";
+ if (!this.shouldLog(normalized)) return;
- console.log(...args);
+ const timestamp = new Date().toISOString();
+ const scopeTag = scope ? `[${scope}]` : "";
+ const sourceTag = source ? `[${source}]` : "";
+ const levelTag = `[${normalized.toUpperCase()}]`;
+ const baseLine = `[${timestamp}] ${levelTag}${scopeTag}${sourceTag} ${message}`;
+ const metaText = this.formatMeta(meta);
+ const logLine = metaText ? `${baseLine} ${metaText}\n` : `${baseLine}\n`;
+
+ const consoleFn =
+ normalized === "error" || normalized === "fatal"
+ ? console.error
+ : normalized === "warn"
+ ? console.warn
+ : console.log;
+
+ if (meta !== undefined) {
+ consoleFn(`${levelTag}${scopeTag}${sourceTag} ${message}`, meta);
+ } else {
+ consoleFn(`${levelTag}${scopeTag}${sourceTag} ${message}`);
+ }
if (this.logStream) {
this.logStream.write(logLine);
}
}
- logReasoning(stage, details) {
- if (!this.debugMode) return;
+ log(...args) {
+ this.write("debug", this.formatArgs(args));
+ }
- const reasoningInfo = {
- stage,
- timestamp: new Date().toISOString(),
- ...details,
- };
+ debug(message, meta, scope, source) {
+ this.write("debug", message, meta, scope, source);
+ }
- // Special formatting for reasoning logs to make them stand out
- console.log(`\nπŸ€– === REASONING ${stage.toUpperCase()} ===`);
- console.log(reasoningInfo);
- console.log(`================================\n`);
+ trace(message, meta, scope, source) {
+ this.write("trace", message, meta, scope, source);
+ }
- this.log(`πŸ€– Reasoning Pipeline - ${stage}`, reasoningInfo);
+ info(message, meta, scope, source) {
+ this.write("info", message, meta, scope, source);
}
- error(...args) {
- if (!this.debugMode) return;
+ warn(message, meta, scope, source) {
+ this.write("warn", message, meta, scope, source);
+ }
- const timestamp = new Date().toISOString();
- const message =
- "❌ ERROR: " +
- args
- .map((arg) =>
- typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
- )
- .join(" ");
+ logReasoning(stage, details) {
+ this.debug(stage, details, "reasoning");
+ }
- const logLine = `[${timestamp}] ${message}\n`;
+ error(...args) {
+ const message = `ERROR: ${this.formatArgs(args)}`;
+ this.write("error", message);
+ }
- console.error(...args);
+ fatal(...args) {
+ const message = `FATAL: ${this.formatArgs(args)}`;
+ this.write("fatal", message);
+ }
- if (this.logStream) {
- this.logStream.write(logLine);
- }
+ logEntry(entry) {
+ if (!entry || typeof entry !== "object") return;
+ const normalized = normalizeLevel(entry.level) || "info";
+ const message = entry.message ? String(entry.message) : "";
+ const scope = entry.scope ? String(entry.scope) : undefined;
+ const source = entry.source ? String(entry.source) : "renderer";
+ this.write(normalized, message, entry.meta, scope, source);
}
logFFmpegDebug(context, ffmpegPath, additionalInfo = {}) {
- if (!this.debugMode) return;
+ if (!this.isDebugEnabled()) return;
const debugInfo = {
context,
@@ -163,23 +283,23 @@ class DebugLogger {
normalized: path.normalize(p),
}));
- this.log(`🎬 FFmpeg Debug - ${context}`, debugInfo);
+ this.debug(`FFmpeg Debug - ${context}`, debugInfo, "ffmpeg");
}
logWindowsPythonSearch(context, details) {
- if (!this.debugMode || process.platform !== "win32") return;
+ if (!this.isDebugEnabled() || process.platform !== "win32") return;
- this.log(`🐍 Windows Python Search - ${context}`, {
+ this.debug(`Windows Python Search - ${context}`, {
...details,
platform: process.platform,
PATH: process.env.PATH?.substring(0, 300) + "...",
LOCALAPPDATA: process.env.LOCALAPPDATA,
ProgramFiles: process.env.ProgramFiles,
- });
+ }, "python");
}
logAudioData(context, audioBlob) {
- if (!this.debugMode) return;
+ if (!this.isDebugEnabled()) return;
const audioInfo = {
context,
@@ -207,13 +327,13 @@ class DebugLogger {
.join(" ");
}
- this.log("πŸ”Š Audio Data Debug", audioInfo);
+ this.debug("Audio Data Debug", audioInfo, "audio");
}
logProcessStart(command, args, options = {}) {
- if (!this.debugMode) return;
+ if (!this.isDebugEnabled()) return;
- this.log("πŸš€ Starting process", {
+ this.debug("Starting process", {
command,
args,
cwd: options.cwd || process.cwd(),
@@ -223,22 +343,21 @@ class DebugLogger {
FFMPEG_BINARY: options.env?.FFMPEG_BINARY,
PATH_preview: options.env?.PATH?.substring(0, 200) + "...",
},
- });
+ }, "process");
}
logProcessOutput(processName, type, data) {
- if (!this.debugMode) return;
+ if (!this.isDebugEnabled()) return;
const output = data.toString().trim();
if (output) {
- this.log(`πŸ“ ${processName} ${type}:`, output);
+ this.debug(`${processName} ${type}`, output, "process");
}
}
logWhisperPipeline(stage, details) {
- if (!this.debugMode) return;
-
- this.log(`πŸŽ™οΈ Whisper Pipeline - ${stage}`, details);
+ if (!this.isDebugEnabled()) return;
+ this.debug(`Whisper Pipeline - ${stage}`, details, "whisper");
}
getLogPath() {
@@ -246,7 +365,7 @@ class DebugLogger {
}
isEnabled() {
- return this.debugMode;
+ return this.isDebugEnabled();
}
close() {
@@ -257,14 +376,6 @@ class DebugLogger {
}
}
- checkDebugFile() {
- try {
- const debugFilePath = path.join(app.getPath("userData"), "ENABLE_DEBUG");
- return fs.existsSync(debugFilePath);
- } catch (e) {
- return false;
- }
- }
}
// Singleton instance
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index babe3e0af..b84f5ed37 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -523,9 +523,12 @@ class IPCHandlers {
}
});
- // Debug logging handler for reasoning pipeline
- ipcMain.handle("log-reasoning", async (event, stage, details) => {
- debugLogger.logReasoning(stage, details);
+ ipcMain.handle("get-log-level", async () => {
+ return debugLogger.getLevel();
+ });
+
+ ipcMain.handle("app-log", async (event, entry) => {
+ debugLogger.logEntry(entry);
return { success: true };
});
}
diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.ts
index be5a7568b..0754c1f30 100644
--- a/src/services/LocalReasoningService.ts
+++ b/src/services/LocalReasoningService.ts
@@ -2,13 +2,7 @@ import modelManager from "../helpers/ModelManager";
import { inferenceConfig } from "../config/InferenceConfig";
import { BaseReasoningService } from "./BaseReasoningService";
import { TOKEN_LIMITS } from "../config/constants";
-
-// Import debugLogger for comprehensive logging
-const debugLogger = {
- logReasoning: (stage: string, details: any) => {
- console.log(`[LOCAL_REASONING ${stage}]`, details);
- }
-};
+import logger from "../utils/logger";
interface LocalReasoningConfig {
maxTokens?: number;
@@ -23,7 +17,7 @@ class LocalReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: LocalReasoningConfig = {}
): Promise<string> {
- debugLogger.logReasoning("LOCAL_MODEL_START", {
+ logger.logReasoning("LOCAL_MODEL_START", {
modelId,
agentName,
textLength: text.length,
@@ -41,7 +35,7 @@ class LocalReasoningService extends BaseReasoningService {
// Get prompt using the base class method
const reasoningPrompt = this.getReasoningPrompt(text, agentName, config);
- debugLogger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {
+ logger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {
promptLength: reasoningPrompt.length,
hasAgentName: !!agentName
});
@@ -57,7 +51,7 @@ class LocalReasoningService extends BaseReasoningService {
TOKEN_LIMITS.TOKEN_MULTIPLIER
);
- debugLogger.logReasoning("LOCAL_MODEL_INFERENCE_CONFIG", {
+ logger.logReasoning("LOCAL_MODEL_INFERENCE_CONFIG", {
modelId,
maxTokens,
temperature: config.temperature || inferenceOptions.temperature,
@@ -74,7 +68,7 @@ class LocalReasoningService extends BaseReasoningService {
const processingTime = Date.now() - startTime;
- debugLogger.logReasoning("LOCAL_MODEL_SUCCESS", {
+ logger.logReasoning("LOCAL_MODEL_SUCCESS", {
modelId,
processingTimeMs: processingTime,
resultLength: result.length,
@@ -85,7 +79,7 @@ class LocalReasoningService extends BaseReasoningService {
} catch (error) {
const processingTime = Date.now() - startTime;
- debugLogger.logReasoning("LOCAL_MODEL_ERROR", {
+ logger.logReasoning("LOCAL_MODEL_ERROR", {
modelId,
processingTimeMs: processingTime,
error: (error as Error).message,
@@ -122,4 +116,4 @@ class LocalReasoningService extends BaseReasoningService {
}
}
-export default new LocalReasoningService();
\ No newline at end of file
+export default new LocalReasoningService();
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index ff75522b3..a89c2ec66 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -3,15 +3,7 @@ import { BaseReasoningService, ReasoningConfig } from "./BaseReasoningService";
import { SecureCache } from "../utils/SecureCache";
import { withRetry, createApiRetryStrategy } from "../utils/retry";
import { API_ENDPOINTS, API_VERSIONS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
-
-// Import debugLogger for comprehensive logging
-const debugLogger = typeof window !== 'undefined' && window.electronAPI
- ? { logReasoning: (stage: string, details: any) => {
- window.electronAPI.logReasoning?.(stage, details).catch(() => {});
- }}
- : { logReasoning: (stage: string, details: any) => {
- console.log(`[REASONING ${stage}]`, details);
- }};
+import logger from "../utils/logger";
export const DEFAULT_PROMPTS = {
agent: `You are {{agentName}}, a helpful AI assistant. Process and improve the following text, removing any reference to your name from the output:\n\n{{text}}\n\nImproved text:`,
@@ -44,7 +36,7 @@ class ReasoningService extends BaseReasoningService {
// Security: Only allow HTTPS endpoints (except localhost for development)
const isLocalhost = normalized.includes('://localhost') || normalized.includes('://127.0.0.1');
if (!normalized.startsWith('https://') && !isLocalhost) {
- debugLogger.logReasoning('OPENAI_BASE_REJECTED', {
+ logger.logReasoning('OPENAI_BASE_REJECTED', {
reason: 'Non-HTTPS endpoint rejected for security',
attempted: normalized
});
@@ -138,7 +130,7 @@ class ReasoningService extends BaseReasoningService {
private async getApiKey(provider: 'openai' | 'anthropic' | 'gemini'): Promise<string> {
let apiKey = this.apiKeyCache.get(provider);
- debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_RETRIEVAL`, {
+ logger.logReasoning(`${provider.toUpperCase()}_KEY_RETRIEVAL`, {
provider,
fromCache: !!apiKey,
cacheSize: this.apiKeyCache.size || 0
@@ -153,7 +145,7 @@ class ReasoningService extends BaseReasoningService {
};
apiKey = await keyGetters[provider]();
- debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_FETCHED`, {
+ logger.logReasoning(`${provider.toUpperCase()}_KEY_FETCHED`, {
provider,
hasKey: !!apiKey,
keyLength: apiKey?.length || 0,
@@ -164,7 +156,7 @@ class ReasoningService extends BaseReasoningService {
this.apiKeyCache.set(provider, apiKey);
}
} catch (error) {
- debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_FETCH_ERROR`, {
+ logger.logReasoning(`${provider.toUpperCase()}_KEY_FETCH_ERROR`, {
provider,
error: (error as Error).message,
stack: (error as Error).stack
@@ -174,7 +166,7 @@ class ReasoningService extends BaseReasoningService {
if (!apiKey) {
const errorMsg = `${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured`;
- debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_MISSING`, {
+ logger.logReasoning(`${provider.toUpperCase()}_KEY_MISSING`, {
provider,
error: errorMsg
});
@@ -192,7 +184,7 @@ class ReasoningService extends BaseReasoningService {
): Promise<string> {
const provider = getModelProvider(model);
- debugLogger.logReasoning("PROVIDER_SELECTION", {
+ logger.logReasoning("PROVIDER_SELECTION", {
model,
provider,
agentName,
@@ -205,7 +197,7 @@ class ReasoningService extends BaseReasoningService {
let result: string;
const startTime = Date.now();
- debugLogger.logReasoning("ROUTING_TO_PROVIDER", {
+ logger.logReasoning("ROUTING_TO_PROVIDER", {
provider,
model
});
@@ -229,7 +221,7 @@ class ReasoningService extends BaseReasoningService {
const processingTime = Date.now() - startTime;
- debugLogger.logReasoning("PROVIDER_SUCCESS", {
+ logger.logReasoning("PROVIDER_SUCCESS", {
provider,
model,
processingTimeMs: processingTime,
@@ -239,7 +231,7 @@ class ReasoningService extends BaseReasoningService {
return result;
} catch (error) {
- debugLogger.logReasoning("PROVIDER_ERROR", {
+ logger.logReasoning("PROVIDER_ERROR", {
provider,
model,
error: (error as Error).message,
@@ -256,7 +248,7 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
- debugLogger.logReasoning("OPENAI_START", {
+ logger.logReasoning("OPENAI_START", {
model,
agentName,
hasApiKey: false // Will update after fetching
@@ -268,7 +260,7 @@ class ReasoningService extends BaseReasoningService {
const apiKey = await this.getApiKey('openai');
- debugLogger.logReasoning("OPENAI_API_KEY", {
+ logger.logReasoning("OPENAI_API_KEY", {
hasApiKey: !!apiKey,
keyLength: apiKey?.length || 0
});
@@ -302,7 +294,7 @@ class ReasoningService extends BaseReasoningService {
const openAiBase = this.getConfiguredOpenAIBase();
const endpointCandidates = this.getOpenAIEndpointCandidates(openAiBase);
- debugLogger.logReasoning("OPENAI_ENDPOINTS", {
+ logger.logReasoning("OPENAI_ENDPOINTS", {
base: openAiBase,
candidates: endpointCandidates.map((candidate) => candidate.url),
preference: this.getStoredOpenAiPreference(openAiBase) || null,
@@ -337,7 +329,7 @@ class ReasoningService extends BaseReasoningService {
if (isUnsupportedEndpoint) {
lastError = new Error(errorMessage);
this.rememberOpenAiPreference(openAiBase, 'chat');
- debugLogger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
+ logger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
attemptedEndpoint: endpoint,
error: errorMessage,
});
@@ -352,7 +344,7 @@ class ReasoningService extends BaseReasoningService {
} catch (error) {
lastError = error as Error;
if (type === 'responses') {
- debugLogger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
+ logger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
attemptedEndpoint: endpoint,
error: (error as Error).message,
});
@@ -372,7 +364,7 @@ class ReasoningService extends BaseReasoningService {
const isChatCompletions = Array.isArray(response?.choices);
// Log the raw response for debugging
- debugLogger.logReasoning("OPENAI_RAW_RESPONSE", {
+ logger.logReasoning("OPENAI_RAW_RESPONSE", {
model,
format: isResponsesApi ? "responses" : isChatCompletions ? "chat_completions" : "unknown",
hasOutput: isResponsesApi,
@@ -432,7 +424,7 @@ class ReasoningService extends BaseReasoningService {
}
}
- debugLogger.logReasoning("OPENAI_RESPONSE", {
+ logger.logReasoning("OPENAI_RESPONSE", {
model,
responseLength: responseText.length,
tokensUsed: response.usage?.total_tokens || 0,
@@ -442,7 +434,7 @@ class ReasoningService extends BaseReasoningService {
// If we got an empty response, return the original text as fallback
if (!responseText) {
- debugLogger.logReasoning("OPENAI_EMPTY_RESPONSE_FALLBACK", {
+ logger.logReasoning("OPENAI_EMPTY_RESPONSE_FALLBACK", {
model,
originalTextLength: text.length,
reason: "Empty response from API"
@@ -452,7 +444,7 @@ class ReasoningService extends BaseReasoningService {
return responseText;
} catch (error) {
- debugLogger.logReasoning("OPENAI_ERROR", {
+ logger.logReasoning("OPENAI_ERROR", {
model,
error: (error as Error).message,
errorType: (error as Error).name
@@ -469,7 +461,7 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
- debugLogger.logReasoning("ANTHROPIC_START", {
+ logger.logReasoning("ANTHROPIC_START", {
model,
agentName,
environment: typeof window !== 'undefined' ? 'browser' : 'node'
@@ -479,7 +471,7 @@ class ReasoningService extends BaseReasoningService {
if (typeof window !== 'undefined' && window.electronAPI) {
const startTime = Date.now();
- debugLogger.logReasoning("ANTHROPIC_IPC_CALL", {
+ logger.logReasoning("ANTHROPIC_IPC_CALL", {
model,
textLength: text.length
});
@@ -489,14 +481,14 @@ class ReasoningService extends BaseReasoningService {
const processingTime = Date.now() - startTime;
if (result.success) {
- debugLogger.logReasoning("ANTHROPIC_SUCCESS", {
+ logger.logReasoning("ANTHROPIC_SUCCESS", {
model,
processingTimeMs: processingTime,
resultLength: result.text.length
});
return result.text;
} else {
- debugLogger.logReasoning("ANTHROPIC_ERROR", {
+ logger.logReasoning("ANTHROPIC_ERROR", {
model,
processingTimeMs: processingTime,
error: result.error
@@ -504,7 +496,7 @@ class ReasoningService extends BaseReasoningService {
throw new Error(result.error);
}
} else {
- debugLogger.logReasoning("ANTHROPIC_UNAVAILABLE", {
+ logger.logReasoning("ANTHROPIC_UNAVAILABLE", {
reason: 'Not in Electron environment'
});
throw new Error('Anthropic reasoning is not available in this environment');
@@ -517,7 +509,7 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
- debugLogger.logReasoning("LOCAL_START", {
+ logger.logReasoning("LOCAL_START", {
model,
agentName,
environment: typeof window !== 'undefined' ? 'browser' : 'node'
@@ -528,7 +520,7 @@ class ReasoningService extends BaseReasoningService {
if (typeof window !== 'undefined' && window.electronAPI) {
const startTime = Date.now();
- debugLogger.logReasoning("LOCAL_IPC_CALL", {
+ logger.logReasoning("LOCAL_IPC_CALL", {
model,
textLength: text.length
});
@@ -538,14 +530,14 @@ class ReasoningService extends BaseReasoningService {
const processingTime = Date.now() - startTime;
if (result.success) {
- debugLogger.logReasoning("LOCAL_SUCCESS", {
+ logger.logReasoning("LOCAL_SUCCESS", {
model,
processingTimeMs: processingTime,
resultLength: result.text.length
});
return result.text;
} else {
- debugLogger.logReasoning("LOCAL_ERROR", {
+ logger.logReasoning("LOCAL_ERROR", {
model,
processingTimeMs: processingTime,
error: result.error
@@ -553,7 +545,7 @@ class ReasoningService extends BaseReasoningService {
throw new Error(result.error);
}
} else {
- debugLogger.logReasoning("LOCAL_UNAVAILABLE", {
+ logger.logReasoning("LOCAL_UNAVAILABLE", {
reason: 'Not in Electron environment'
});
throw new Error('Local reasoning is not available in this environment');
@@ -566,7 +558,7 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
- debugLogger.logReasoning("GEMINI_START", {
+ logger.logReasoning("GEMINI_START", {
model,
agentName,
hasApiKey: false
@@ -578,7 +570,7 @@ class ReasoningService extends BaseReasoningService {
const apiKey = await this.getApiKey('gemini');
- debugLogger.logReasoning("GEMINI_API_KEY", {
+ logger.logReasoning("GEMINI_API_KEY", {
hasApiKey: !!apiKey,
keyLength: apiKey?.length || 0
});
@@ -613,7 +605,7 @@ class ReasoningService extends BaseReasoningService {
try {
response = await withRetry(
async () => {
- debugLogger.logReasoning("GEMINI_REQUEST", {
+ logger.logReasoning("GEMINI_REQUEST", {
endpoint: `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`,
model,
hasApiKey: !!apiKey,
@@ -642,7 +634,7 @@ class ReasoningService extends BaseReasoningService {
errorData = { error: errorText || res.statusText };
}
- debugLogger.logReasoning("GEMINI_API_ERROR_DETAIL", {
+ logger.logReasoning("GEMINI_API_ERROR_DETAIL", {
status: res.status,
statusText: res.statusText,
error: errorData,
@@ -656,7 +648,7 @@ class ReasoningService extends BaseReasoningService {
const jsonResponse = await res.json();
- debugLogger.logReasoning("GEMINI_RAW_RESPONSE", {
+ logger.logReasoning("GEMINI_RAW_RESPONSE", {
hasResponse: !!jsonResponse,
responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],
hasCandidates: !!jsonResponse?.candidates,
@@ -669,7 +661,7 @@ class ReasoningService extends BaseReasoningService {
createApiRetryStrategy("Gemini")
);
} catch (fetchError) {
- debugLogger.logReasoning("GEMINI_FETCH_ERROR", {
+ logger.logReasoning("GEMINI_FETCH_ERROR", {
error: (fetchError as Error).message,
stack: (fetchError as Error).stack
});
@@ -678,7 +670,7 @@ class ReasoningService extends BaseReasoningService {
// Check if response has the expected structure
if (!response.candidates || !response.candidates[0]) {
- debugLogger.logReasoning("GEMINI_RESPONSE_ERROR", {
+ logger.logReasoning("GEMINI_RESPONSE_ERROR", {
model,
response: JSON.stringify(response).substring(0, 500),
hasCandidate: !!response.candidates,
@@ -690,7 +682,7 @@ class ReasoningService extends BaseReasoningService {
// Check if the response has actual content
const candidate = response.candidates[0];
if (!candidate.content?.parts?.[0]?.text) {
- debugLogger.logReasoning("GEMINI_EMPTY_RESPONSE", {
+ logger.logReasoning("GEMINI_EMPTY_RESPONSE", {
model,
finishReason: candidate.finishReason,
hasContent: !!candidate.content,
@@ -707,7 +699,7 @@ class ReasoningService extends BaseReasoningService {
const responseText = candidate.content.parts[0].text.trim();
- debugLogger.logReasoning("GEMINI_RESPONSE", {
+ logger.logReasoning("GEMINI_RESPONSE", {
model,
responseLength: responseText.length,
tokensUsed: response.usageMetadata?.totalTokenCount || 0,
@@ -716,7 +708,7 @@ class ReasoningService extends BaseReasoningService {
return responseText;
} catch (error) {
- debugLogger.logReasoning("GEMINI_ERROR", {
+ logger.logReasoning("GEMINI_ERROR", {
model,
error: (error as Error).message,
errorType: (error as Error).name
@@ -735,7 +727,7 @@ class ReasoningService extends BaseReasoningService {
const geminiKey = await window.electronAPI?.getGeminiKey?.();
const localAvailable = await window.electronAPI?.checkLocalReasoningAvailable?.();
- debugLogger.logReasoning("API_KEY_CHECK", {
+ logger.logReasoning("API_KEY_CHECK", {
hasOpenAI: !!openaiKey,
hasAnthropic: !!anthropicKey,
hasGemini: !!geminiKey,
@@ -748,7 +740,7 @@ class ReasoningService extends BaseReasoningService {
return !!(openaiKey || anthropicKey || geminiKey || localAvailable);
} catch (error) {
- debugLogger.logReasoning("API_KEY_CHECK_ERROR", {
+ logger.logReasoning("API_KEY_CHECK_ERROR", {
error: (error as Error).message,
stack: (error as Error).stack,
name: (error as Error).name
@@ -764,4 +756,4 @@ class ReasoningService extends BaseReasoningService {
}
}
-export default new ReasoningService();
\ No newline at end of file
+export default new ReasoningService();
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 2a1f9708a..058462734 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -280,7 +280,14 @@ declare global {
saveGeminiKey: (key: string) => Promise<void>;
// Debug logging
- logReasoning?: (stage: string, details: any) => Promise<void>;
+ getLogLevel?: () => Promise<string>;
+ log?: (entry: {
+ level: string;
+ message: string;
+ meta?: any;
+ scope?: string;
+ source?: string;
+ }) => Promise<void>;
// FFmpeg availability
checkFFmpegAvailability: () => Promise<boolean>;
diff --git a/src/utils/debugLoggerRenderer.js b/src/utils/debugLoggerRenderer.js
deleted file mode 100644
index c32958f06..000000000
--- a/src/utils/debugLoggerRenderer.js
+++ /dev/null
@@ -1,40 +0,0 @@
-// Shared debug logger for renderer process
-const createDebugLogger = (prefix = "REASONING") => {
- return {
- isDebugMode: null, // Cache debug mode status
-
- async checkDebugMode() {
- if (this.isDebugMode === null && typeof window !== 'undefined' && window.electronAPI?.getDebugMode) {
- try {
- this.isDebugMode = await window.electronAPI.getDebugMode();
- } catch {
- this.isDebugMode = false;
- }
- }
- return this.isDebugMode || false;
- },
-
- async logReasoning(stage, details) {
- // Only log if debug mode is enabled
- const debugEnabled = await this.checkDebugMode();
- if (!debugEnabled) return;
-
- if (typeof window !== 'undefined' && window.electronAPI?.logReasoning) {
- try {
- await window.electronAPI.logReasoning(stage, details);
- } catch (error) {
- console.error('Failed to log reasoning:', error);
- }
- } else {
- // Fallback to console if IPC not available
- console.log(`πŸ€– [${prefix} ${stage}]`, details);
- }
- },
-
- clearCache() {
- this.isDebugMode = null;
- }
- };
-};
-
-export default createDebugLogger;
\ No newline at end of file
diff --git a/src/utils/logger.ts b/src/utils/logger.ts
new file mode 100644
index 000000000..7c353e8c4
--- /dev/null
+++ b/src/utils/logger.ts
@@ -0,0 +1,110 @@
+type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
+
+const LOG_LEVELS: Record<LogLevel, number> = {
+ trace: 10,
+ debug: 20,
+ info: 30,
+ warn: 40,
+ error: 50,
+ fatal: 60,
+};
+
+const normalizeLevel = (value?: string | null): LogLevel | null => {
+ if (!value) return null;
+ const lower = value.toLowerCase();
+ return lower in LOG_LEVELS ? (lower as LogLevel) : null;
+};
+
+const defaultLevel: LogLevel = "info";
+
+let cachedLevel: LogLevel | null = null;
+let levelPromise: Promise<LogLevel> | null = null;
+
+const resolveLogLevel = async (): Promise<LogLevel> => {
+ if (cachedLevel) {
+ return cachedLevel;
+ }
+ if (!levelPromise) {
+ levelPromise = (async () => {
+ if (typeof window !== "undefined" && window.electronAPI?.getLogLevel) {
+ try {
+ const level = normalizeLevel(await window.electronAPI.getLogLevel());
+ if (level) {
+ cachedLevel = level;
+ return level;
+ }
+ } catch {
+ // Fall back to default level
+ }
+ }
+ cachedLevel = defaultLevel;
+ return cachedLevel;
+ })();
+ }
+ return levelPromise;
+};
+
+const shouldLog = (level: LogLevel, current: LogLevel) => {
+ return LOG_LEVELS[level] >= LOG_LEVELS[current];
+};
+
+const logToConsole = (level: LogLevel, message: string, meta?: any, scope?: string) => {
+ const levelTag = `[${level.toUpperCase()}]`;
+ const scopeTag = scope ? `[${scope}]` : "";
+ const consoleFn =
+ level === "error" || level === "fatal"
+ ? console.error
+ : level === "warn"
+ ? console.warn
+ : console.log;
+ if (meta !== undefined) {
+ consoleFn(`${levelTag}${scopeTag} ${message}`, meta);
+ } else {
+ consoleFn(`${levelTag}${scopeTag} ${message}`);
+ }
+};
+
+const log = async (level: LogLevel, message: string, meta?: any, scope?: string) => {
+ const currentLevel = await resolveLogLevel();
+ if (!shouldLog(level, currentLevel)) return;
+
+ if (typeof window !== "undefined" && window.electronAPI?.log) {
+ try {
+ await window.electronAPI.log({
+ level,
+ message: String(message),
+ meta,
+ scope,
+ source: "renderer",
+ });
+ return;
+ } catch {
+ // Fall back to console
+ }
+ }
+
+ logToConsole(level, String(message), meta, scope);
+};
+
+const logger = {
+ trace: (message: string, meta?: any, scope?: string) =>
+ log("trace", message, meta, scope),
+ debug: (message: string, meta?: any, scope?: string) =>
+ log("debug", message, meta, scope),
+ info: (message: string, meta?: any, scope?: string) =>
+ log("info", message, meta, scope),
+ warn: (message: string, meta?: any, scope?: string) =>
+ log("warn", message, meta, scope),
+ error: (message: string, meta?: any, scope?: string) =>
+ log("error", message, meta, scope),
+ fatal: (message: string, meta?: any, scope?: string) =>
+ log("fatal", message, meta, scope),
+ logReasoning: (stage: string, details?: any) =>
+ log("debug", stage, details, "reasoning"),
+ refreshLogLevel: () => {
+ cachedLevel = null;
+ levelPromise = null;
+ },
+};
+
+export default logger;